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

后端 未结 14 933
北恋
北恋 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:45

    I recently switch to set strict-mode -version 2.0 and my null tests failed.

    I added a function:

    #use in strict mode to validate property exists before using
    function exists {
      param($obj,$prop)
      try {
        if ($null -ne $obj[$prop]) {return $true}
        return $false
      } catch {
        return $false
      }
      return $false
    }
    

    Now I code

    if (exists $run main) { ...
    

    rather than

    if ($run.main -ne $null) { ...
    

    and we are on our way. Seems to work on objects and hashtables

    As an unintended benefit it is less typing.

提交回复
热议问题