スクリーンキャプチャを行う

PowerShellでスクリーンキャプチャを行うサンプルです。

スクリーンキャプチャを行う(JPEG

[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") 
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 

function saveScreenCapture([String]$outputPath)
{
	$rect = [System.windows.forms.Screen]::PrimaryScreen.Bounds
	$bitmap = new-object System.Drawing.Bitmap( `
		$rect.Width, `
		$rect.Height, `
		[System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
	$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
	$graphics.CopyFromScreen( `
		$rect.X, `
		$rect.Y, `
		0, `
		0, `
		$rect.Size, `
		[System.Drawing.CopyPixelOperation]::SourceCopy)
	$bitmap.Save($outputPath, [System.Drawing.Imaging.ImageFormat]::Jpeg)
}


使い方は

saveScreenCapture [出力ファイルのフルパス]

です。

保存形式は・・・

$bitmap.Saveの第2引数を変えることで、JPGE以外のフォーマットも利用可能です。
保存可能なフォーマットは、以下を実行すると分かります。

ImageFormatの一覧を取得する
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[System.Drawing.Imaging.ImageFormat] | gm -static -membertype property
出力結果
   TypeName: System.Drawing.Imaging.ImageFormat

Name      MemberType Definition
----      ---------- ----------
Bmp       Property   static System.Drawing.Imaging.ImageFormat Bmp {get;}
Emf       Property   static System.Drawing.Imaging.ImageFormat Emf {get;}
Exif      Property   static System.Drawing.Imaging.ImageFormat Exif {get;}
Gif       Property   static System.Drawing.Imaging.ImageFormat Gif {get;}
Icon      Property   static System.Drawing.Imaging.ImageFormat Icon {get;}
Jpeg      Property   static System.Drawing.Imaging.ImageFormat Jpeg {get;}
MemoryBmp Property   static System.Drawing.Imaging.ImageFormat MemoryBmp {get;}
Png       Property   static System.Drawing.Imaging.ImageFormat Png {get;}
Tiff      Property   static System.Drawing.Imaging.ImageFormat Tiff {get;}
Wmf       Property   static System.Drawing.Imaging.ImageFormat Wmf {get;}