PowerShell Tidbit: Capturing a ScreenShot with PowerShell

This is a crude approach but works for capturing the main window of an application who’s process object you can find –typically via Get-Process.  If you run this script from PowerShell.exe or PowerShell_ISE.exe you will capture a screen shot of the host application’s main window which will get saved to your $home folder as screenshot.bmp.


$src = @'
using System;
using System.Runtime.InteropServices;

namespace PInvoke
{
public static class NativeMethods
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
}

[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
}
'
@


Add-Type -TypeDefinition $src
Add-Type -AssemblyName System.Drawing

# Get a process object from which we will get the main window bounds
$iseProc = Get-Process -id $pid

$bmpScreenCap = $g = $null
try {
$rect = new-object PInvoke.RECT
if ([PInvoke.NativeMethods]::GetWindowRect($iseProc.MainWindowHandle, [ref]$rect))
{
$width = $rect.Right - $rect.Left + 1
$height = $rect.Bottom - $rect.Top + 1
$bmpScreenCap = new-object System.Drawing.Bitmap $width,$height
$g = [System.Drawing.Graphics]::FromImage($bmpScreenCap)
$g.CopyFromScreen($rect.Left, $rect.Top, 0, 0, $bmpScreenCap.Size,
[System.Drawing.CopyPixelOperation]::SourceCopy)
$bmpScreenCap.Save("$home\screenshot.bmp")
}
}
finally {
if ($bmpScreenCap) { $bmpScreenCap.Dispose() }
if ($g) { $g.Dispose() }
}

Have fun.

About these ads
This entry was posted in PowerShell, PowerShell 3.0, PowerShell 4.0. Bookmark the permalink.

3 Responses to PowerShell Tidbit: Capturing a ScreenShot with PowerShell

  1. Pingback: Microsoft Most Valuable Professional (MVP) – Best Posts of the Week around Windows Server, Exchange, SystemCenter and more – #51 - Flo's Datacenter Report

  2. Pingback: Microsoft Most Valuable Professional (MVP) – Best Posts of the Week around Windows Server, Exchange, SystemCenter and more – #51 - Dell TechCenter - TechCenter - Dell Community

  3. Pingback: How you can take screenshots in Windows 8.1 and save them straight to the hard drive. | Securitron Linux blog.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s