user1178954
user1178954

Reputation: 7

Checking for null arrays in an PSObject

How would I go about Checking for Null or empty in an Object that has multiple arrays?

$buildings.North = {bld1,bld2,bld3}
$buildings.South = {}
$buildings.East = {bld5,bld6}
$buildings.West = {bld7,bld8,bld9,bld10}

I started out with a if / elseif to go through each one, but that would be 16 combinations of this:

if ($Buildings.North.count -eq "0" -and $Buildings.South.count -ge "1" -and $Buildings.East.count -ge "1" -and $Buildings.West.count -ge "1" ){set-function -OPT1 $Buildings.South -OPT2 $Buildings.East -OPT3 $Buildings.West }
elseif ($Buildings.North.count -ge "1" -and $Buildings.South.count -ge "1" -and $Buildings.East.count -ge "1" -and $Buildings.West.count -ge "1" ){set-function -OPT1 $Buildings.North -OPT2 $Buildings.South -OPT3 $Buildings.East -OPT4 $Buildings.West}
elseif ($Buildings.North.count -eq "0" -and $Buildings.South.count -eq "0" -and $Buildings.East.count -eq "0"  -and $Buildings.West.count -eq "0"){#empty do nothing}
elseif ($Buildings.North.count -eq "0" -and $Buildings.South.count -eq "0" -and $Buildings.East.count -ge "1" -and $Buildings.West.count -ge "1" ){set-function -OPT3 $Buildings.East -OPT4 $Buildings.West}

Since you could have hundreds of options in a object, that could be a lot of code. I also tried to build the cmd, out of a string:

$cmd = ' -Location $Loc' 
if ($Buildings.North.count -ge "1"){ $cmd += ' -OPT1 $Buildings.North ' }
elseif ($Buildings.South.count -ge "1"){$cmd += ' -OPT2 $Buildings.South'}
elseif ($Buildings.East.count -ge "1"){$cmd += ' -OPT3 $Buildings.East'}
elseif ($Buildings.West.count -ge "1"){$cmd += ' -OPT4 $Buildings.West'}
Set-Function $cmd 

Not much success with this approach either. There has to be a better way to do this sort of checking, help finding it would be most appreciated.

Upvotes: 0

Views: 3080

Answers (3)

E.V.I.L.
E.V.I.L.

Reputation: 2166

#Create Test Object
$buildings = New-Object -TypeName psobject -Property @{'North'=@('a','b');'south'=@('x');'West'=@()}

#Returns arrays that are not 0 in count
$buildings | Get-Member -MemberType NoteProperty | ? {($buildings.($_.name)).count}

Upvotes: 0

mjolinor
mjolinor

Reputation: 68273

$Opts = @{
OPT1 = $buildings.North
OPT2 = $buildings.South
OPT3 = $buildings.East
OPT4 = $buildings.West
}

$opts.GetEnumerator() |
foreach {if (-not $_.value){$opts.Remove($_.Name)}}

Set-Function @Opts 

FWIW

Upvotes: 0

Tomas Panik
Tomas Panik

Reputation: 4609

this should work:

$cmd = ' -Location `$Loc' 
if ($Buildings.North.count -ge "1"){ $cmd += ' -OPT1 `$Buildings.North ' }
elseif ($Buildings.South.count -ge "1"){$cmd += ' -OPT2 `$Buildings.South'}
elseif ($Buildings.East.count -ge "1"){$cmd += ' -OPT3 `$Buildings.East'}
elseif ($Buildings.West.count -ge "1"){$cmd += ' -OPT4 `$Buildings.West'}
Invoke-Expression "Set-Function $cmd"

Upvotes: 2

Related Questions