Testing for property existance

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 3 years, 1 month ago.

  • Author
    Posts
  • #13434
    Profile photo of davidski
    davidski
    Participant

    Is there a simple way to test if a property exists on a given object under PoSH 3?

    I have a number of cmdlets which return objects with alternate sets of properties, depending on their results. In my scripts, I'd like to test for the existence of those properties within if statements, but PoSH returns errors on the property not existing. This has been a long running frustration that I Google for every couple of months to no avail. The only options seem to involve convolutions around try/catch blocks or writing helper functions that parse through the properties on objects. Both of those approaches potentially meet my functional requirements, but it seems like an awful lot of code and scaffolding for a simple -exists style function. Is there a simpler PoSH method to meet this goal? How do others solve what I would think would be a common problem?

    David

  • #13435
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Well, my developer answer would be that your command output should be considered a contract, and should be consistent, even if some properties sometimes have null values. Or, give your output object a type name that describes the kind of object it is. Then you can easily look at the type name and know what properties to expect.

    To answer your question, pipe the object to GM and capture the output. Yo can easily see what properties exist that way.

  • #13436
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    I assume you're using Set-StrictMode, if you're getting errors when you try to access a non-existent property. By default, PowerShell just returns $null when you do that.

    To test for the existence of a property, you can use the PSObject.Properties table:

    $testObject = New-Object psobject -Property @{
        SomeProperty = 'SomeValue'
    }
    
    if ($testObject.PSObject.Properties['SomeProperty'])
    {
        Write-Host "SomeProperty: $($testObject.SomeProperty)"
    }
    
    if ($testObject.PSObject.Properties['BogusProperty'])
    {
        Write-Host "BogusProperty: $($testObject.BogusProperty)"
    }
    

    Edit: Get-Member works too, as Don mentioned:

    if (Get-Member -InputObject $testObject -Name SomeProperty -MemberType Properties)
    {
        Write-Host "SomeProperty: $($testObject.SomeProperty)"
    }
    

You must be logged in to reply to this topic.