2013-03-20 32 views
0

我該如何去檢查具有多個數組的對象中的空或空?檢查PSObject中的空數組

$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 

這種方法也沒有太大的成功。必須有更好的方法來進行這種檢查,幫助找到它將是最受讚賞的。

回答

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" 
+0

調用,表達!啊!這有助於使功能正常工作。謝謝。你碰巧對如何在這種類型的對象設置中檢查null(或不爲空)有任何想法。我開始越來越多地使用對象,並且我不能想出一種方法來做這種檢查,而不是很長的if/elseif條件。 – user1178954 2013-03-20 21:48:06

+0

@ user1178954:如果它解決了您的問題,請不要忘記將此答案標記爲已接受。 – Neolisk 2013-03-21 00:14:01

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

+0

謝謝!這對於這種事情很有效。 – user1178954 2013-03-21 12:27:38

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

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