下面的test2和test3结果是不同的。
我对此感到困惑,因为它看起来像相同的逻辑,并且与linux bash ||
逻辑不同。
$data = @(
[PSCustomObject]@{State="TAIPEI";Type="1"}
[PSCustomObject]@{State="TAIPEI";Type="2"}
[PSCustomObject]@{State="KH";Type="3"}
[PSCustomObject]@{State="KH";Type="4"}
[PSCustomObject]@{State="KH";Type="5"}
[PSCustomObject]@{State="TX";Type="6"}
[PSCustomObject]@{State="TX";Type="7"}
)
$json = $data | ConvertTo-Json ;
# test1
$g = $data | Group State;
Write-Host($g.Length); #result : 3
# test2
$g = $json | ConvertFrom-Json | Group State ;
Write-Host($g.Length); #result : 1
# test3
$g = $json | ConvertFrom-Json ;
$g = $g | Group State ;
Write-Host($g.Length); #result : 3
Try it online!我尝试过的
我用vscode Debug模式检查变量
test1是[Object [3]]和3 GroupInfo
test2成为收藏
test3是[Object [3]]和3 GroupInfo
最佳答案
我首先在Powershell 7中尝试了您的示例,但无法重现您的结果,所有操作均按预期进行。因此,这似乎仅限于Powershell 5。
查看两个版本中的ConvertFrom-Json
输出的内容,您可以看到发生了什么:
在Powershell 7中:
# ~> $json | ConvertFrom-Json | get-member
TypeName: System.Management.Automation.PSCustomObject
在Powershell 5.1中:# ~> $json | ConvertFrom-Json | Get-Member
TypeName: System.Object[]
因此,看起来在Powershell 5.1中ConvertFrom-Json
不会输出PSCustomObject
需要正常运行的Group-Object
。我发现了一种简单的解决方法,可以将ConvertFrom-Json
的输出转换为PSCustomObject
的工作方式:# ~> $g = $json | ConvertFrom-Json | %{[PsCustomObject]$_} | group state
# ~> $g
Count Name Group
----- ---- -----
2 TAIPEI {@{State=TAIPEI; Type=1}, @{State=TAIPEI; Type=2}}
3 KH {@{State=KH; Type=3}, @{State=KH; Type=4}, @{State=KH; Type=5}}
2 TX {@{State=TX; Type=6}, @{State=TX; Type=7}}
或者,您可以只使用Powershell 7。
关于powershell - PowerShell “$g = $json | ConvertFrom-Json | Group State”结果与 “$g = $json | ConvertFrom-Json ; $g = $g | Group State ;”不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64284015/