Remote Screenshot

by jaredatkinson at 2013-04-03 17:54:05

I am trying to write a script that will take a screenshot on a remote system utilizing .NET code over WinRM.

I found this example code on a blog to take a screenshot using PowerShell

$ScreenBounds = [Windows.Forms.SystemInformation]::VirtualScreen
$ScreenshotObject = New-Object Drawing.Bitmap $ScreenBounds.Width, $ScreenBounds.Height
$DrawingGraphics = [Drawing.Graphics]::FromImage($ScreenshotObject)
$DrawingGraphics.CopyFromScreen($ScreenBounds.Location, [Drawing.Point]::Empty, $ScreenBounds.Size)
$DrawingGraphics.Dispose()
$ScreenshotObject.Save(C:\temp\screenshot.png)
$ScreenshotObject.Dispose()


This code works when run locally, but when it is run through the Invoke-Command Cmdlet it returns an error ‘Exception Calling "CopyFromScreen" with three arguments: "The handle is invalid"’. The error is listed as a MethodInvocationException

Below is a copy of the code I used to run the script remotely (on the localhost for simplicity of testing)

$scriptblock = {
$ScreenBounds = [Windows.Forms.SystemInformation]::VirtualScreen
$ScreenshotObject = New-Object Drawing.Bitmap $ScreenBounds.Width, $ScreenBounds.Height
$DrawingGraphics = [Drawing.Graphics]::FromImage($ScreenshotObject)
$DrawingGraphics.CopyFromScreen($ScreenBounds.Location, [Drawing.Point]::Empty, $ScreenBounds.Size)
$DrawingGraphics.Dispose()
$ScreenshotObject.Save(C:\temp\screenshot.png)
$ScreenshotObject.Dispose()
}
Invoke-Command -scriptblock {Param($scriptblock) Invoke-Expression $scriptblock} -ArgumentList $scriptblock -computername localhost


I understand the file would be saved to the file system of the remote host, but the issue is that the file is not being written because of an exception caused by the CopyFromScreen method.
by mjolinor at 2013-04-03 18:10:34
There is no "screen" to take a screenshot of in a remote session. If you’re expecting to get a screenshot of what’s on the local user’s monitor, this is not going to work. It’s executing in a completely separate session and runspace and cannot access the user’s session.

Solution here:

https://powershell.org/forums/topic/take-screenshot-of-a-remote-users-desktop