0

我将如何检查具有多个数组的对象中的 Null 或空?

$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 

这种方法也没有太大的成功。必须有更好的方法来进行这种检查,帮助找到它将不胜感激。

4

3 回答 3

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"
于 2013-03-20T21:32:42.623 回答
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

于 2013-03-20T22:53:20.187 回答
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}
于 2013-03-21T05:23:37.090 回答