Background
Playing around with Powershell and ran into an error that one should avoid through defensive programming.
Error
Error – Image
Error – Text
The property 'nationality' cannot be found on this object. Verify that the property exists. At property\customObject.property.ps1:57 char:33 + Write-Host "`tNationality: '$($person.nationality)'"; + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], PropertyNotFoundException + FullyQualifiedErrorId : PropertyNotFoundStrict Nationality: ''
Outline
- We will create a few standalone objects using PSCustomObject
- Add created objects into an array
- Iterate through the array
- Access each object
- Retrieve property
- Because our object’s properties are created on the fly, there is no inherent type checking
- On our last object, we will intentionally skip setting the nationality property
Code
Set-StrictMode -Version 2.0 # initialize the array [PsObject[]]$objCandidate = @() $objHuman1 = [pscustomobject]@{ name='L.L. Cool J'; gender='M'; nationality='American'; } $objHuman2 = [pscustomobject]@{ name='Fresh Prince'; gender='M'; nationality='American'; } $objHuman3 = [pscustomobject]@{ name='Slick Rick'; gender='M'; } $objCandidate += $objHuman1; $objCandidate += $objHuman2; $objCandidate += $objHuman3; foreach($person in $objCandidate) { Write-Host "`tName:- '$($person.Name)'"; Write-Host "`tGender:- '$($person.gender)'"; Write-Host "`tNationality: '$($person.nationality)'"; Write-Host ""; }
Workaround
Outline
- Get a list of the object’s properties name
- Perform an “in” search against the list
Code
[string] $propertyNationality = 'nationality'; function hasProperty($object, $propertyName) { $hasProperty = $propertyName -in $object.PSobject.Properties.Name; return($hasProperty); } foreach($person in $objCandidate) { # Does object have property $propNationalityExists = hasProperty $person $propertyNationality; Write-Host "`tName:- '$($person.Name)'"; Write-Host "`tGender:- '$($person.gender)'"; if ( ($propNationalityExists -eq $True) { Write-Host "`tNationality: '$($person.nationality)'"; } Write-Host ""; }
Crediting
dan-gph
Code Sharing
GitHub
Repository
DanielAdeniji/powershell.customObject