How can you test if an object has a specific property?

后端 未结 14 826
北恋
北恋 2020-12-25 09:01

How can you test if an object has a specific property?

Appreciate I can do ...

$members = Get-Member -InputObject $myobject 

and th

14条回答
  •  隐瞒了意图╮
    2020-12-25 09:39

    Just check against null.

    ($myObject.MyProperty -ne $null)
    

    If you have not set PowerShell to StrictMode, this works even if the property does not exist:

    $obj = New-Object PSObject;                                                   
    Add-Member -InputObject $obj -MemberType NoteProperty -Name Foo -Value "Bar";
    $obj.Foo; # Bar                                                                  
    ($obj.MyProperty -ne $null);  # False, no exception
    

提交回复
热议问题