How to Take Screenshot on Remote Desktop Using Powershell

I have written a code, which is opening a browser and taking a screenshot. But when I running it through remote desktop, it's taking blank image.

Can anyone suggest, how can I take the screenshot of browser on the remote desktop through PowerShell ?

for e.g. I need to open on remote desktop and save screenshot in that remote server.

Code:

[Reflection.Assembly]::LoadWithPartialName("System.Drawing")
function screenshot([Drawing.Rectangle]$bounds, $path) {
   $bmp = New-Object Drawing.Bitmap $bounds.width, $bounds.height
   $graphics = [Drawing.Graphics]::FromImage($bmp)

   $graphics.CopyFromScreen($bounds.Location, [Drawing.Point]::Empty, $bounds.size)

   $bmp.Save($path)

   $graphics.Dispose()
   $bmp.Dispose()
}
10

1 Answer

What you are trying to do can't be directly performed remotely

When I say "remotely" here, I mean you can't invoke the screen capture from one system to another. The code has to be executed in a local context.

Ultimately, you'll need to run $graphics.CopyFromScreen() from a user who is also logged into the Desktop, not just over a PSRemoting session. There's literally nothing GUI-wise to capture; the remoting session has no GUI components loaded on the other side. In short, you can't expect to use PSRemoting to capture a remote screenshot. It's not happening, there is no screen to copy from, and should result in a Win32Exception: "The handle is invalid". This occurs any time you attempt to copy the screen buffer (screen buffer is different than the display buffer) from a PSRemoting session, even if the user is logged in via RDP at the same time.

Note: My testing indicates the screen capture should still work over RDP without modification to your existing code. I am not sure whether there are GPOs or other settings which can prevent this from working.

However, if the logon session exists but is inactive (e.g. RDP client disconnected), you will get the same "Invalid handle" error. This answer sheds some more light on the behavior, but basically you need to have an active user session to have the draw context copied from. Without this, there is no draw context and thus there is no valid handle to obtain the graphics data from.

There is a possible solution using the Win32 API to perform an interactive logon as another user and then execute your PowerShell script (also with a Win32 API call), I have more information about that further in this answer.


Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.