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

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

    Real similar to a javascript check:

    foreach($member in $members)
    {
        if($member.PropertyName)
        {
            Write $member.PropertyName
        }
        else
        {
            Write "Nope!"
        }
    }
    
    0 讨论(0)
  • 2020-12-25 09:39

    For me MyProperty" -in $MyObject.PSobject.Properties.Name didn't work, however

    $MyObject.PSobject.Properties.Name.Contains("MyProperty")
    

    works

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-25 09:40

    I ended up with the following function ...

    function HasNoteProperty(
        [object]$testObject,
        [string]$propertyName
    )
    {
        $members = Get-Member -InputObject $testObject 
        if ($members -ne $null -and $members.count -gt 0) 
        { 
            foreach($member in $members) 
            { 
                if ( ($member.MemberType -eq "NoteProperty" )  -and `
                     ($member.Name       -eq $propertyName) ) 
                { 
                    return $true 
                } 
            } 
            return $false 
        } 
        else 
        { 
            return $false; 
        }
    }
    
    0 讨论(0)
  • 2020-12-25 09:43

    Like this?

     [bool]($myObject.PSobject.Properties.name -match "myPropertyNameToTest")
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题