调用不存在的属性时,为什么不返回错误?

时间:2013-09-19 17:51:08

标签: powershell

给出以下代码段

$drives = Get-PSDrive

foreach($drive in $drives)
{
    Write-Host $drive.Name "`t" $drive.Root
    Write-Host " - " $drive.Free "`t" $drive.PropertyDoesntExist
}   

drive.PropertyDoesntExist属性不... erm ...存在所以我希望抛出一个错误,而是返回一个null。

我如何获得错误或例外?

编辑 - 我很糟糕 - 我在一个问题中提出了2个问题,因此我将其中的一个问题移到了separate question

1 个答案:

答案 0 :(得分:4)

NextHop Blog为这个问题提供了一个很好的解决方案。它不会给你一个错误,而是一个布尔值。您可以使用Get-Member获取对象类型的所有真实属性的集合,然后匹配您想要的属性。

以下是字符串的示例:

PS C:\> $test = "I'm a string."
PS C:\> ($test | Get-Member | Select-Object -ExpandProperty Name) -contains "Trim"
True
PS C:\> ($test | Get-Member | Select-Object -ExpandProperty Name) -contains "Pigs"
False

如果您明确要错误,可能需要将Set-Strictmode视为Set-StrictMode -version 2以捕获不存在的属性。您也可以在完成后轻松关闭它:

PS C:\> Set-StrictMode -version 2
PS C:\> "test".Pigs
Property 'Pigs' cannot be found on this object. Make sure that it exists.
At line:1 char:8
+ "test". <<<< Pigs
    + CategoryInfo          : InvalidOperation: (.:OperatorToken) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFoundStrict

PS C:\> Set-StrictMode -off
相关问题