在 PowerShell 中,单个项目数组在返回时展开,请参阅:关于数组你想知道的一切 https://learn.microsoft.com/powershell/scripting/learn/deep-dives/everything-about-arrays.
写输出-NoEnumerate https://learn.microsoft.com/powershell/scripting/learn/deep-dives/everything-about-arrays#write-output--noenumerate
PowerShell 喜欢解开或枚举数组。这是 PowerShell 使用管道方式的核心方面,但有时您不希望这种情况发生。
这可能是最大的陷阱/陷阱 https://stackoverflow.com/q/11107428/1701026在 PowerShell 中并且不特定于ConvertFrom-Json https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertfrom-jsoncmdlet,请参阅例如:当调用仅返回一个对象时,如何强制 Powershell 返回一个数组? https://stackoverflow.com/q/11107428/1701026.
强制数组的最简单(也是最常见)的方法是使用数组子表达式运算符@( ) https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#array-subexpression-operator--(而不是分组运算符( ) https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#grouping-operator--):
@('["bogus"]' | ConvertFrom-Json).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
e.g.:
@('["bogus"]' | ConvertFrom-Json)[0]
bogus
另请参阅以下问题:展开数组单个“数组子表达式运算符” https://stackoverflow.com/search?q=%5Bpowershell%5D+unroll+array+single+%22Array+subexpression+operator%22
As 马克门0 https://stackoverflow.com/users/45375/mklement0指出这有帮助ConvertFrom-Json 解压包含 1 个项目的数组,并且对于空对象表现奇怪 https://stackoverflow.com/a/76996546/1701026答案,您可能还会注意到此行为与 PowerShell 7+ 之前的版本之间的差异。