Pul*_*kit 9 powershell json powershell-3.0
我正在尝试编写一个PowerShell脚本来读取文件并打印"true"如果它是一个有效的JSON文件.我正在使用Powershell v3.0,这就是我现在所拥有的:
$text = Get-Content .\filename.txt -Raw
$powershellRepresentation = $text | ConvertFrom-Json
Run Code Online (Sandbox Code Playgroud)
如何查看返回代码?我的意思是我想要这样的东西:
if(file not a JSON file){
Write-Host "not JSON"
}
else{
Write-Host "True"
}
Run Code Online (Sandbox Code Playgroud)
Nai*_*gel 12
没有Test-Json类似cmdlet,因此最好的方法是将ConvertFrom-Jsoncmdlet放在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";
}
Run Code Online (Sandbox Code Playgroud)
如果您遇到此问题并且可以使用 PowerShell 6 或更高版本,现在有一个 Test-Json cmdlet。它还不仅可以验证它是有效的 JSON,还可以使用-Schemaparam验证它是否符合特定的 JSON 模式。
$isValid = Get-Content .\filename.txt -Raw | Test-Json
if($isValid){
Write-Host "not JSON"
}
else{
Write-Host "True"
}
Run Code Online (Sandbox Code Playgroud)
希望通过以下方式验证 ARM 模板的用户的说明-Schema(我无法想象更完美的用例)。在撰写本文时,Test-Json用于验证的底层库NJsonSchema 中存在一个或多个错误,并且无法验证 ARM 模板。