问题描述
编写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-NullWrite-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 GreenWrite-Host \"\"Write-Host \"==== 循环打印List中所有元素结果 ==== \" -ForegroundColor DarkYellowforeach( $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-Nullforeach( $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 GreenWrite-Host \"\"Write-Host \"==== 循环打印List中所有元素结果 ==== \" -ForegroundColor DarkYellowforeach( $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