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

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

    I've been using the following which returns the property value, as it would be accessed via $thing.$prop, if the "property" would be to exist and not throw a random exception. If the property "doesn't exist" (or has a null value) then $null is returned: this approach functions in/is useful for strict mode, because, well, Gonna Catch 'em All.

    I find this approach useful because it allows PS Custom Objects, normal .NET objects, PS HashTables, and .NET collections like Dictionary to be treated as "duck-typed equivalent", which I find is a fairly good fit for PowerShell.

    Of course, this does not meet the strict definition of "has a property".. which this question may be explicitly limited to. If accepting the larger definition of "property" assumed here, the method can be trivially modified to return a boolean.

    Function Get-PropOrNull {
        param($thing, [string]$prop)
        Try {
            $thing.$prop
        } Catch {
        }
    }
    

    Examples:

    Get-PropOrNull (Get-Date) "Date"                   # => Monday, February 05, 2018 12:00:00 AM
    Get-PropOrNull (Get-Date) "flub"                   # => $null
    Get-PropOrNull (@{x="HashTable"}) "x"              # => "HashTable"
    Get-PropOrNull ([PSCustomObject]@{x="Custom"}) "x" # => "Custom"
    $oldDict = New-Object "System.Collections.HashTable"
    $oldDict["x"] = "OldDict"
    Get-PropOrNull $d "x"                              # => "OldDict"
    

    And, this behavior might not [always] be desired.. ie. it's not possible to distinguish between x.Count and x["Count"].

提交回复
热议问题