【问题标题】:How do I evaluate if data or an error returned in PowerShell?如何评估 PowerShell 中是否返回数据或错误?
【发布时间】:2020-12-17 20:38:06
【问题描述】:

我正在尝试使用以下 cmdlet 测试 Powershell 中是否存在 DNS 区域:

Get-DNSServerZone abc.com

这很好用,但我现在需要做的是根据是否存在错误或是否返回数据将其转换为真/假评估。

例如,这是一个真实的场景:

$a = Get-DnsServerZone abc.com
$a

ZoneName                            ZoneType        IsAutoCreated   IsDsIntegrated  IsReverseLookupZone  IsSigned
--------                            --------        -------------   --------------  -------------------  --------
abc.com                            Secondary       False           False           False

这是一个错误的场景:

$a = Get-DnsServerZone def.com
Get-DnsServerZone : The zone def.com was not found on server DNSSERVER1.
At line:1 char:6
+ $a = Get-DnsServerZone def.com
+      ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (def.com:root/Microsoft/...S_DnsServerZone) [Get-DnsServerZone], CimException
+ FullyQualifiedErrorId : WIN32 9601,Get-DnsServerZone

我正在苦苦挣扎的是如何评估它?用外行的话来说,我需要检查$a 是否有实际数据。

非常感谢!

【问题讨论】:

    标签: powershell


    【解决方案1】:

    我现在需要做的是根据是否有错误或是否返回数据将其转换为真/假评估。

    如果您可以简单地忽略失败并且不需要Get-DNSServerZone返回的对象,您可以执行以下操作:

    $zoneExist = [bool] (Get-DNSServerZone abc.com -ErrorAction Ignore)
    
    • -ErrorAction Ignore 悄悄地忽略任何(非终止)错误。

    • 投射[bool]Get-DNSServerZone 的输出映射到$true(输出描述区域的对象)或$false(没有输出(到成功输出流),因为发生了错误),采取PowerShell 的implicit to-Boolean conversion 的优势。

    如果你也想要区域描述对象:

    $zoneExist = [bool] ($zoneInfo = Get-DNSServerZone abc.com -ErrorAction Ignore)
    

    另一种方法是先捕获区域信息,然后查询automatic $? variable,其中包含一个布尔值($true$false),指示最近执行的语句是否导致任何错误(是否压制与否)。

    $zoneInfo = Get-DNSServerZone abc.com -ErrorAction Ignore
    $zoneExist = $?
    

    【讨论】:

    • 非常感谢!这对于理解 PS 中的错误处理非常有帮助。我不知道你可以这样查询$?
    • 很高兴听到它有帮助,@DominicBrunetti;我的荣幸。还有一个提示:try / catch 只能捕获 terminating 错误,但您可以使用-ErrorAction Stop 将非终止错误提升为终止错误,如 Theo 的回答。有关 PowerShell 异常复杂的错误处理的全面概述,请参阅 this GitHub docs issue
    【解决方案2】:

    您可以将其包装在 try..catch 中:

    try {
        Get-DNSServerZone abc.com -ErrorAction Stop
    }
    catch {
        Write-Warning "zone abc.com doesn't exist"
    }
    

    或者反过来忽略错误:

    $a = Get-DNSServerZone abc.com -ErrorAction SilentlyContinue
    if (!$a) {
        Write-Warning "abc.com doesn't exist"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 2021-04-04
      相关资源
      最近更新 更多