Solved

Powershell. Take a screenshot then email script

Posted on 2015-01-10
14
1,793 Views
Last Modified: 2015-01-11
I have this powershell script that used to work to save a picture of my screen but it doesn't work anymore, I also wanted to see if I could get it email me the picture instead of saving it.

. .\Take-ScreenShot.ps1

Take-ScreenShot -screen -file "C:\image.png" -imagetype png

I got the script off here -> https://gallery.technet.microsoft.com/scriptcenter/eeff544a-f690-4f6b-a586-11eea6fc5eb8

 
Function Take-ScreenShot { 
    <#   
.SYNOPSIS   
    Used to take a screenshot of the desktop or the active window.  
.DESCRIPTION   
    Used to take a screenshot of the desktop or the active window and save to an image file if needed. 
.PARAMETER screen 
    Screenshot of the entire screen 
.PARAMETER activewindow 
    Screenshot of the active window 
.PARAMETER file 
    Name of the file to save as. Default is image.bmp 
.PARAMETER imagetype 
    Type of image being saved. Can use JPEG,BMP,PNG. Default is bitmap(bmp)   
.PARAMETER print 
    Sends the screenshot directly to your default printer       
.INPUTS 
.OUTPUTS     
.NOTES   
    Name: Take-ScreenShot 
    Author: Boe Prox 
    DateCreated: 07/25/2010      
.EXAMPLE   
    Take-ScreenShot -activewindow 
    Takes a screen shot of the active window         
.EXAMPLE   
    Take-ScreenShot -Screen 
    Takes a screenshot of the entire desktop 
.EXAMPLE   
    Take-ScreenShot -activewindow -file "C:\image.bmp" -imagetype bmp 
    Takes a screenshot of the active window and saves the file named image.bmp with the image being bitmap 
.EXAMPLE   
    Take-ScreenShot -screen -file "C:\image.png" -imagetype png     
    Takes a screenshot of the entire desktop and saves the file named image.png with the image being png 
.EXAMPLE   
    Take-ScreenShot -Screen -print 
    Takes a screenshot of the entire desktop and sends to a printer 
.EXAMPLE   
    Take-ScreenShot -ActiveWindow -print 
    Takes a screenshot of the active window and sends to a printer     
#>   
#Requires -Version 2 
        [cmdletbinding( 
                SupportsShouldProcess = $True, 
                DefaultParameterSetName = "screen", 
                ConfirmImpact = "low" 
        )] 
Param ( 
       [Parameter( 
            Mandatory = $False, 
            ParameterSetName = "screen", 
            ValueFromPipeline = $True)] 
            [switch]$screen, 
       [Parameter( 
            Mandatory = $False, 
            ParameterSetName = "window", 
            ValueFromPipeline = $False)] 
            [switch]$activewindow, 
       [Parameter( 
            Mandatory = $False, 
            ParameterSetName = "", 
            ValueFromPipeline = $False)] 
            [string]$file,  
       [Parameter( 
            Mandatory = $False, 
            ParameterSetName = "", 
            ValueFromPipeline = $False)] 
            [string] 
            [ValidateSet("bmp","jpeg","png")] 
            $imagetype = "bmp", 
       [Parameter( 
            Mandatory = $False, 
            ParameterSetName = "", 
            ValueFromPipeline = $False)] 
            [switch]$print                        
        
) 
# C# code 
$code = @' 
using System; 
using System.Runtime.InteropServices; 
using System.Drawing; 
using System.Drawing.Imaging; 
namespace ScreenShotDemo 
{ 
  /// <summary> 
  /// Provides functions to capture the entire screen, or a particular window, and save it to a file. 
  /// </summary> 
  public class ScreenCapture 
  { 
    /// <summary> 
    /// Creates an Image object containing a screen shot the active window 
    /// </summary> 
    /// <returns></returns> 
    public Image CaptureActiveWindow() 
    { 
      return CaptureWindow( User32.GetForegroundWindow() ); 
    } 
    /// <summary> 
    /// Creates an Image object containing a screen shot of the entire desktop 
    /// </summary> 
    /// <returns></returns> 
    public Image CaptureScreen() 
    { 
      return CaptureWindow( User32.GetDesktopWindow() ); 
    }     
    /// <summary> 
    /// Creates an Image object containing a screen shot of a specific window 
    /// </summary> 
    /// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param> 
    /// <returns></returns> 
    private Image CaptureWindow(IntPtr handle) 
    { 
      // get te hDC of the target window 
      IntPtr hdcSrc = User32.GetWindowDC(handle); 
      // get the size 
      User32.RECT windowRect = new User32.RECT(); 
      User32.GetWindowRect(handle,ref windowRect); 
      int width = windowRect.right - windowRect.left; 
      int height = windowRect.bottom - windowRect.top; 
      // create a device context we can copy to 
      IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc); 
      // create a bitmap we can copy it to, 
      // using GetDeviceCaps to get the width/height 
      IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height); 
      // select the bitmap object 
      IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap); 
      // bitblt over 
      GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY); 
      // restore selection 
      GDI32.SelectObject(hdcDest,hOld); 
      // clean up 
      GDI32.DeleteDC(hdcDest); 
      User32.ReleaseDC(handle,hdcSrc); 
      // get a .NET image object for it 
      Image img = Image.FromHbitmap(hBitmap); 
      // free up the Bitmap object 
      GDI32.DeleteObject(hBitmap); 
      return img; 
    } 
    /// <summary> 
    /// Captures a screen shot of the active window, and saves it to a file 
    /// </summary> 
    /// <param name="filename"></param> 
    /// <param name="format"></param> 
    public void CaptureActiveWindowToFile(string filename, ImageFormat format) 
    { 
      Image img = CaptureActiveWindow(); 
      img.Save(filename,format); 
    } 
    /// <summary> 
    /// Captures a screen shot of the entire desktop, and saves it to a file 
    /// </summary> 
    /// <param name="filename"></param> 
    /// <param name="format"></param> 
    public void CaptureScreenToFile(string filename, ImageFormat format) 
    { 
      Image img = CaptureScreen(); 
      img.Save(filename,format); 
    }     
    
    /// <summary> 
    /// Helper class containing Gdi32 API functions 
    /// </summary> 
    private class GDI32 
    { 
       
      public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter 
      [DllImport("gdi32.dll")] 
      public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest, 
        int nWidth,int nHeight,IntPtr hObjectSource, 
        int nXSrc,int nYSrc,int dwRop); 
      [DllImport("gdi32.dll")] 
      public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth, 
        int nHeight); 
      [DllImport("gdi32.dll")] 
      public static extern IntPtr CreateCompatibleDC(IntPtr hDC); 
      [DllImport("gdi32.dll")] 
      public static extern bool DeleteDC(IntPtr hDC); 
      [DllImport("gdi32.dll")] 
      public static extern bool DeleteObject(IntPtr hObject); 
      [DllImport("gdi32.dll")] 
      public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject); 
    } 
 
    /// <summary> 
    /// Helper class containing User32 API functions 
    /// </summary> 
    private class User32 
    { 
      [StructLayout(LayoutKind.Sequential)] 
      public struct RECT 
      { 
        public int left; 
        public int top; 
        public int right; 
        public int bottom; 
      } 
      [DllImport("user32.dll")] 
      public static extern IntPtr GetDesktopWindow(); 
      [DllImport("user32.dll")] 
      public static extern IntPtr GetWindowDC(IntPtr hWnd); 
      [DllImport("user32.dll")] 
      public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC); 
      [DllImport("user32.dll")] 
      public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect); 
      [DllImport("user32.dll")] 
      public static extern IntPtr GetForegroundWindow();       
    } 
  } 
} 
'@ 
#User Add-Type to import the code 
add-type $code -ReferencedAssemblies 'System.Windows.Forms','System.Drawing' 
#Create the object for the Function 
$capture = New-Object ScreenShotDemo.ScreenCapture 
 
#Take screenshot of the entire screen 
If ($Screen) { 
    Write-Verbose "Taking screenshot of entire desktop" 
    #Save to a file 
    If ($file) { 
        If ($file -eq "") { 
            $file = "$pwd\image.bmp" 
            } 
        Write-Verbose "Creating screen file: $file with imagetype of $imagetype" 
        $capture.CaptureScreenToFile($file,$imagetype) 
        } 
    ElseIf ($print) { 
        $img = $Capture.CaptureScreen() 
        $pd = New-Object System.Drawing.Printing.PrintDocument 
        $pd.Add_PrintPage({$_.Graphics.DrawImage(([System.Drawing.Image]$img), 0, 0)}) 
        $pd.Print() 
        }         
    Else { 
        $capture.CaptureScreen() 
        } 
    } 
#Take screenshot of the active window     
If ($ActiveWindow) { 
    Write-Verbose "Taking screenshot of the active window" 
    #Save to a file 
    If ($file) { 
        If ($file -eq "") { 
            $file = "$pwd\image.bmp" 
            } 
        Write-Verbose "Creating activewindow file: $file with imagetype of $imagetype" 
        $capture.CaptureActiveWindowToFile($file,$imagetype) 
        } 
    ElseIf ($print) { 
        $img = $Capture.CaptureActiveWindow() 
        $pd = New-Object System.Drawing.Printing.PrintDocument 
        $pd.Add_PrintPage({$_.Graphics.DrawImage(([System.Drawing.Image]$img), 0, 0)}) 
        $pd.Print() 
        }         
    Else { 
        $capture.CaptureActiveWindow() 
        }     
    }      
}

Open in new window

0
Comment
Question by:Network Zero
  • 7
  • 4
  • 2
14 Comments
 
LVL 44

Expert Comment

by:Rainer Jeschor
ID: 40542391
Hi,
which Powershell version / which OS are you targeting?
What kind of error do you get?

It runs fine on my Windows 8.1.

For sending an email and attach the stored screenshot, you can use the built-in cmdlet
Send-Mailmessage
(available since Powershell V3)

HTH
Rainer
0
 
LVL 7

Author Comment

by:Network Zero
ID: 40542696
I don't get any errors, the command runs without any issues just does nothing.

I'm using with windows 10 with powershell 5.0 and server 2012 r2 with powershell 4.0

both have .net 4.5+ - I also tried sta mode

I tried changing the path and different folders

No screen shot or anything is saved in any folder
Screenshot-1.png
0
 
LVL 44

Expert Comment

by:Rainer Jeschor
ID: 40542822
Hi,
as far as I read the script, if you pass the -file parameter it has to be a complete filename meaning path and file name and file extension - from your screenshot it looks like you pass just a path (folder).

I have currently no Windows 10 or Srv 2012 R2 at hand to verify.
HTH
Rainer
0
 
LVL 68

Expert Comment

by:Qlemo
ID: 40543116
Rainer, Send-MailMessage is available since PS 2 ;-)
But you are correct about the file name parameter - it needs to be a full path plus file name.


BTW, this code part is useless
    If ($file) { 
        If ($file -eq "") { 
            $file = "$pwd\image.bmp" 
            } 

Open in new window

because with $file = "" the if($file) is false.
I also wonder why the only value from a pipeline should be the -screen switch - does not make much sense to me ...
0
 
LVL 7

Author Comment

by:Network Zero
ID: 40543120
Ok guys I tried this but it does nothing.... as well.. I think I tried it before.. Maybe it has to do with my default screen capture ... I don't know..

I attached the pictures.. does the script work for you Qlemo?
powershell2.png
0
 
LVL 68

Accepted Solution

by:
Qlemo earned 500 total points
ID: 40543151
Most simple solution is to save the screenshot to a temporary file, then attach that file to the mail sent.
In theory you could also embed the image data as Base64 encoded string into a simple HTML page, but doing that needs quite some conversions, and has size and display limitations. Or short, a screenshot will most likely not work as embedded image.
$tmpfile = "$env:Temp\ScreenShot.png"
Take-ScreenShot -activeWindow -file $tmpfile -imageType 'png'
Send-MailMessage -SmtpServer smtp.YourDomain.com -From You@YourDomain.com -To You@YourDomain.Com -Subject "A screenshot" -Attachments $tmpfile
Remove-Item $tmpfile

Open in new window

0
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
LVL 68

Expert Comment

by:Qlemo
ID: 40543165
Just tested. It works as long as I provide either -Screen or -ActiveWindow. It doesn't do anything without those. Add -verbose to see if the script recognizes your parameters.
You do not need STA - that is only required in rare occassions where you need to use Windows.Forms directly to build and manage a dialog or the like.
0
 
LVL 7

Author Comment

by:Network Zero
ID: 40543169
$tmpfile = "$env:Temp\ScreenShot.png"
Take-ScreenShot -activeWindow -file $tmpfile -imageType 'png'
Send-MailMessage -SmtpServer smtp.YourDomain.com -From You@YourDomain.com -To You@YourDomain.Com -Subject "A screenshot" -Attachments $tmpfile
Remove-Item $tmpfile

Open in new window


OK I'm going on one of the servers to try it. THANKS!
0
 
LVL 7

Author Comment

by:Network Zero
ID: 40543202
For some Reason the Take-screenshot script doesn't work for me anywhere.... I can't find where the picture goes and the script can't either. I switched the script with this get-screenshot script.

Everything is working when I use get screen shot. So I added the code to email.ps1 I run it in powershell I get the email no problem but i set it up in task scheduler so I can get emails of the attachments I do get the emails but the attachments are blank now...

$tmpfile = "$env:Temp\ScreenShot.png"
./get-ScreenShot 
Send-MailMessage -SmtpServer smtp.YourDomain.com -From You@YourDomain.com -To You@YourDomain.Com -Subject "A screenshot" -Attachments $tmpfile
Remove-Item $tmpfile

Open in new window




function Get-ScreenShot
{
    [CmdletBinding()]
    param(
        [parameter(
            Position  = 0,
            Mandatory = 0,
            ValueFromPipelinebyPropertyName = 1)]
        [ValidateNotNullOrEmpty()]
        [string]
        $OutPath = "$env:USERPROFILE\Documents\ScreenShot",
 
        #screenshot_[yyyyMMdd_HHmmss_ffff].png
        [parameter(
            Position  = 1,
            Mandatory = 0,
            ValueFromPipelinebyPropertyName = 1)]
        [ValidateNotNullOrEmpty()]
        [string]
        $FileNamePattern = 'screenshot_{0}.png',
 
        [parameter(
            Position  = 2,
            Mandatory = 0,
            ValueFromPipeline = 1,
            ValueFromPipelinebyPropertyName = 1)]
        [ValidateNotNullOrEmpty()]
        [int]
        $RepeatTimes = 0,
 
        [parameter(
            Position  = 3,
            Mandatory = 0,
            ValueFromPipelinebyPropertyName = 1)]
        [ValidateNotNullOrEmpty()]
        [int]
        $DurationMs = 1
     )
 
     begin
     {
        $ErrorActionPreference = 'Stop'
        Add-Type -AssemblyName System.Windows.Forms
 
        if (-not (Test-Path $OutPath))
        {
            New-Item $OutPath -ItemType Directory -Force
        }
     }
 
     process
     {
        1..$RepeatTimes `
        | %{
            $fileName = $FileNamePattern -f (Get-Date).ToString('yyyyMMdd_HHmmss_ffff')
            $path = Join-Path $OutPath $fileName
 
            $b = New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width, [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height)
            $g = [System.Drawing.Graphics]::FromImage($b)
            $g.CopyFromScreen((New-Object System.Drawing.Point(0,0)), (New-Object System.Drawing.Point(0,0)), $b.Size)
            $g.Dispose()
            $b.Save($path)
 
            if ($RepeatTimes -ne 0)
            {
                Start-Sleep -Milliseconds $DurationMs
            }
        }
    }
}

Open in new window

0
 
LVL 7

Author Comment

by:Network Zero
ID: 40543203
I mean the attachment is a picture of a blank screen * just white*
0
 
LVL 68

Expert Comment

by:Qlemo
ID: 40543213
That might be an issue with the task. Don't know if a task has access to the current session or screen. You tried by setting up the task as running with your current credentials and highest privileges?
0
 
LVL 7

Author Comment

by:Network Zero
ID: 40543232
I had it running highest privileges - I noticed that if I run it running "run only when user is logged in" it works but the box pops up.

Only when I have it with or without the user logged in it doesn't work.(the picture is blank)

I tried adding this parameter: powershell -File myScript.ps1 -WindowStyle Hidden

It still comes up.  I have it logged in as the admin that I'm logged in as.
0
 
LVL 7

Author Closing Comment

by:Network Zero
ID: 40543257
powershell.exe -windowstyle hidden -file C:\ps\email.ps1 Adding this final argument !!!

YESS SIR !!!!
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Utilizing an array to gracefully append to a list of EmailAddresses
I thought I'd write this up for anyone who has a request to create an anonymous whistle-blower-type submission form created using SharePoint 2010 (this would probably work the same for 2013). It's not 100% fool-proof but it's as close as you can get…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now