检查PSObject中的空数组

时间:2013-03-20 20:59:37

标签: powershell

如何在具有多个数组的Object中检查Null或empty?

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

我从if / elseif开始经历每一个,但这将是16个组合:

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}

由于对象中可能有数百个选项,因此可能需要大量代码。我还尝试用字符串构建cmd:

$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 

这种方法也没有太大的成功。必须有一种更好的方法来进行这种检查,帮助找到它将是最受欢迎的。

3 个答案:

答案 0 :(得分:2)

这应该有效:

$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"

答案 1 :(得分:0)

$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

答案 2 :(得分:0)

#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}