Skip to content

Instantly share code, notes, and snippets.

@jschell
Created August 15, 2025 22:19
Show Gist options
  • Select an option

  • Save jschell/1ebb38d3bcaeefd4bb89f09d7eb2606b to your computer and use it in GitHub Desktop.

Select an option

Save jschell/1ebb38d3bcaeefd4bb89f09d7eb2606b to your computer and use it in GitHub Desktop.
function Get-ScreenCapture
{
<#
.SYNOPSIS
There are prettier ways to run screencaps, but this is fast and for audit controls <shrug>
.NOTES
#### Name: Get-ScreenCapture
#### Author: J Schell
#### Version: 0.1.0
#### License: MIT
### Change Log
##### 2019-04-18::0.1.0
- initial create
#>
[CmdletBinding()]
Param
(
$ProcessID = $PID,
$Path = $pwd
)
Begin
{
$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
}
Process
{
$targetProcess = Get-Process -id $ProcessID
$bmpScreenCap = $null
$graphics = $null
try
{
$rect = new-object PInvoke.RECT
if ([PInvoke.NativeMethods]::GetWindowRect($targetProcess.MainWindowHandle, [ref]$rect))
{
$width = $rect.Right - $rect.Left + 1
$height = $rect.Bottom - $rect.Top + 1
$bmpScreenCap = new-object System.Drawing.Bitmap $width,$height
$graphics = [System.Drawing.Graphics]::FromImage($bmpScreenCap)
$graphics.CopyFromScreen($rect.Left, $rect.Top, 0, 0, $bmpScreenCap.Size,
[System.Drawing.CopyPixelOperation]::SourceCopy)
$shortDateString = (Get-Date).toString('s').Replace(':','.')
$bmpScreenCap.Save("$Path\$($shortDateString)-screencap.bmp")
}
}
finally
{
if ($bmpScreenCap) { $bmpScreenCap.Dispose() }
if ($graphics) { $graphics.Dispose() }
}
}
End
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment