【Azure Developer】使用PowerShell Where-Object方法過濾多維ArrayList時候,遇見的詭異問題 — 當查找結果只有一個對象時,返回結果修改了對象結構,把多維變為一維

問題描述

編寫PowerShell腳本,以多維(3維)數組中第二維度的值進行過濾,並打印出結果

#三維數組源數據

「A」, 「11」, 「Cheng Du」
「B」, 「21」, 「Chong Qing」
「C」, 「31」, 「Shang Hai」
「D」, 「41」, 「Bei Jing」
「E」, 「51」, 「Nan Jing」

#從地址中過濾以Chong開頭的地區, 結果需要為
B, 21, Chong Qing

PowerShell腳本為:

$CityList = [System.Collections.ArrayList]::new()
$CityList.Add(@(「A」,「11」,「Cheng Du」)) | Out-Null
$CityList.Add(@(「B」,「21」,「Chong Qing」)) | Out-Null
$CityList.Add(@(「C」,「31」,「Shang Hai」)) | Out-Null
$CityList.Add(@(「D」,「41」,「Bei Jing」)) | Out-Null
$CityList.Add(@(「E」,「51」,「Nan Jing」)) | Out-Null


Write-Host "==== 開始過濾 Chong  ==== " -ForegroundColor DarkYellow
$FinalCityList = $CityList | Where-object -filterScript {$_[2] -like "Chong*"}

Write-Host "Final City List 類型" -ForegroundColor Green
$FinalCityList.GetType()

Write-Host "Final City 數量為: " $FinalCityList.Count -ForegroundColor Green
Write-Host ""
Write-Host "==== 循環打印List中所有元素結果 ==== "  -ForegroundColor DarkYellow
foreach( $aaa in $FinalCityList)
{
    Write-Host $aaa[0]','$aaa[1]','$aaa[2]
}

Write-Host ""
Write-Host "==== 直接輸出對象的結果 ==== " -ForegroundColor red
$FinalCityList

輸出結果 :當過濾結果大於1時,顯示正常,當過濾結果為1時,結果顯示異常。結果變成了一個一位數組,Count結果為3。

 

這是為什麼呢?

 

問題分析

從 $FinalCityList 的打印結果分析,當 Where-Object 查看到結果只有一個的時候,就把結果對象進行了多維到一維的轉換。所以結果變為了一個包含三行內容的一位數組。

問題解決

$FinalCityList = @($CityList | Where-object -filterScript {$_[2] -like "Chong*"})

把 Where-Object 方法用 @()  進行對象轉換即可。

 

 

完整的PowerShell腳本為:

$CityList = [System.Collections.ArrayList]::new()
$CityList.Add(@(「A」,「11」,「Cheng Du」)) | Out-Null
$CityList.Add(@(「B」,「21」,「Chong Qing」)) | Out-Null
$CityList.Add(@(「C」,「31」,「Shang Hai」)) | Out-Null
$CityList.Add(@(「D」,「41」,「Bei Jing」)) | Out-Null
$CityList.Add(@(「E」,「51」,「Nan Jing」)) | Out-Null
foreach( $ccc in $CityList)
{
    Write-Host $ccc[0]','$ccc[1]','$ccc[2]
}

Write-Host "==== 開始過濾 CityList 中包含 Chong 的城市  ==== " -ForegroundColor Yellow
$FinalCityList = @($CityList | Where-object -filterScript {$_[2] -like "Chong*"})

Write-Host "Final City List 類型" -ForegroundColor Green
$FinalCityList.GetType()

Write-Host "Final City 數量為: " $FinalCityList.Count -ForegroundColor Green
Write-Host ""
Write-Host "==== 循環打印List中所有元素結果 ==== "  -ForegroundColor DarkYellow
foreach( $aaa in $FinalCityList)
{
    Write-Host $aaa[0]','$aaa[1]','$aaa[2]
}

Write-Host ""

Write-Host "==== 直接輸出對象的結果 ==== " -ForegroundColor red
$FinalCityList

 

參考文檔

數組子表達式運算符:  //docs.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_arrays?view=powershell-7.2#the-array-sub-expression-operator

What does the “@” symbol do in PowerShell?://stackoverflow.com/questions/363884/what-does-the-symbol-do-in-powershell