Powershell 在json文件数组上使用测试json

Powershell 在json文件数组上使用测试json,powershell,Powershell,我正在尝试使用Powershell 6中的Test json Cmdlet验证文件夹中的所有json文件: [array]$myFiles=Get-ChildItem *.json -Recurse| select -expand fullname foreach ($filePath in $myFiles) { try { $isValid = Get-Content $filePath -Raw | Test-Json $working = $true } catch { $w

我正在尝试使用Powershell 6中的Test json Cmdlet验证文件夹中的所有json文件:

[array]$myFiles=Get-ChildItem *.json -Recurse| select -expand fullname

foreach ($filePath in $myFiles)
{

try {
 $isValid = Get-Content $filePath -Raw | Test-Json
 $working = $true
 } catch {
 $working = $false
 }

if ($working) {
Write-Host "Is working for $filePath"
}
else {
Write-Host "Not working for $filePath"

}
}
如果json文件不正确,cmdlet Test json将显示一个错误,该错误引用的是.ps1文件而不是.json文件,因此与$filePath一起使用的是有效的还是无效的

但是,不管json文件是否正确,它都表示所有json文件都适用。 因此,我需要要么为工作,要么不为工作,才能正常工作,或者如果我能让测试Json显示错误的Json文件,而不是.ps1文件,那就更好了

有什么帮助吗?

问题在于使用测试Json

根据您的代码片段,您似乎认为,如果JSON格式不正确,它将抛出错误,而事实并非如此。测试JSON生成的错误将打印在控制台上,但不会抛出异常

在您的情况下,Test-Json cmdlet将只返回True或False值,并且错误消息将打印在控制台上

以下是您的代码的更正版本:

[array]$myFiles=Get-ChildItem *.json -Recurse| select -expand fullname

foreach ($filePath in $myFiles)
{
    $isValid = Get-Content $filePath -Raw | Test-Json -ErrorAction SilentlyContinue

    if ($isValid) 
    {
        Write-Host "Is working for $filePath"
    }
    else 
    {
        Write-Host "Not working for $filePath"
    }
}
请访问此处了解更多关于、此处和此处的信息。

问题在于使用测试Json

根据您的代码片段,您似乎认为,如果JSON格式不正确,它将抛出错误,而事实并非如此。测试JSON生成的错误将打印在控制台上,但不会抛出异常

在您的情况下,Test-Json cmdlet将只返回True或False值,并且错误消息将打印在控制台上

以下是您的代码的更正版本:

[array]$myFiles=Get-ChildItem *.json -Recurse| select -expand fullname

foreach ($filePath in $myFiles)
{
    $isValid = Get-Content $filePath -Raw | Test-Json -ErrorAction SilentlyContinue

    if ($isValid) 
    {
        Write-Host "Is working for $filePath"
    }
    else 
    {
        Write-Host "Not working for $filePath"
    }
}

访问此处了解有关、此处、此处的更多信息。

捕获块从不使用默认错误操作首选项设置执行:为什么不使用$working=|直接测试Json?catch块从不使用默认错误操作首选项设置执行:为什么不使用$working=|直接测试Json?谢谢更新。谢谢更新。