下記を参考にして、powershellで連番の「ディスクの管理」画面のスクリーンショットを取得しようとしています。
参照URL:PowerShellでアクティブウィンドウをキャプチャ
https://qiita.com/mitazet/items/878709ee7407df41d78c
コード
#キャプチャ関数
function Get-ScreenCapture($name)
{
begin {
Add-Type -AssemblyName System.Drawing, System.Windows.Forms
$jpegCodec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() |
Where-Object { $_.FormatDescription -eq "JPEG" }
}
process {
Start-Sleep -Milliseconds 250
#Alt+PrintScreenを送信 [Windows.Forms.Sendkeys]::SendWait("%{PrtSc}") Start-Sleep -Milliseconds 250 #クリップボードから画像をコピー $bitmap = [Windows.Forms.Clipboard]::GetImage() #画像保存(名前がかぶらないようにしている) $ep = New-Object Drawing.Imaging.EncoderParameters $ep.Param[0] = New-Object Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality, [long]100) $screenCapturePathBase = "$env:USERPROFILE\Desktop\${name}" $c = 1 while (Test-Path "${screenCapturePathBase}_${c}.jpg") { $c++ } $bitmap.Save("${screenCapturePathBase}_${c}.jpg", $jpegCodec, $ep) }
}
ディスクの管理起動
C:\Windows\System32\diskmgmt.msc
待機
Start-Sleep -Milliseconds 3000
画面取得
Get-ScreenCapture disk
exit
うまくいく時もあれば、以下のようなエラーが出て取得できない時もあります。
エラー内容:
null 値の式ではメソッドを呼び出せません。
発生場所xxxxxxxxxxxxxxxxxxxx :42 文字:9
$bitmap.Save("${screenCapturePathBase}_${c}.jpg", $jpegCodec, $ep)
CategoryInfo :InvalidOperation: (:) []、RuntimeException
FullyQualifiedErrorID : InvokeMethodOnNull
原因が分からず困っています。コードの修正でエラーなく常に正常終了させることは出来ますでしょうか。
よろしくお願いします。
あなたの回答
tips
プレビュー