UPDATE 2021: PowerShell 6 以降のバージョン
PowerShell 6 では、まったく新しいTest-Jsonコマンドレットが提供されます。ここに参照があります。
Test-Json生のファイル コンテンツをコマンドレットに直接渡すだけです。
$text = Get-Content .\filename.txt -Raw
if ($text | Test-Json) {
$powershellRepresentation = ConvertFrom-Json $text -ErrorAction Stop;
Write-Host "Provided text has been correctly parsed to JSON";
} else {
Write-Host "Provided text is not a valid JSON string";
}
PowerShell 5 以前のバージョン
Test-Jsonこれらのバージョンにはコマンドレットがないため、コマンドレットをブロックConvertFrom-Json内に配置するのが最善の方法ですtry ... catch
try {
$powershellRepresentation = ConvertFrom-Json $text -ErrorAction Stop;
$validJson = $true;
} catch {
$validJson = $false;
}
if ($validJson) {
Write-Host "Provided text has been correctly parsed to JSON";
} else {
Write-Host "Provided text is not a valid JSON string";
}