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

路邊兩盞燈發表於2022-03-30

問題描述

編寫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 檢視到結果只有一個的時候,就把結果物件進行了多維到一維的轉換。所以結果變為了一個包含三行內容的一位陣列。

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

問題解決

$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

 

參考文件

陣列子表示式運算子:  https://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?:https://stackoverflow.com/questions/363884/what-does-the-symbol-do-in-powershell

 

 

相關文章