powershell - PowerShell “$g = $json | ConvertFrom-Json | Group State”结果与 “$g = $json | ConvertFrom-Json ; $g = $g | Group State ;”不同

标签 powershell

下面的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/

相关文章:

json - 如何使用变量访问 powershell PSCustomObject 变量(来自 json)

xml - 如何使用Powershell循环创建XML文件的元素?

powershell - Out-Gridview 去除下划线

json - 如何为azure虚拟机创建数据盘?

powershell - parseexact在Powershell中将所有内容转换为一月份

PowerShell 对多个参数进行过滤

powershell - PowerShell 的 -Version 参数到底有什么作用?

testing - 在 Windows Powershell 中选择用于 Web UI 测试自动化的下拉列表选项

powershell - 修剪命令输出

powershell - 从powershell显示exe安装进度?