Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PowerShell cmdlet。一个元素结果的长度属性_Powershell_For Loop_Cmdlets - Fatal编程技术网

PowerShell cmdlet。一个元素结果的长度属性

PowerShell cmdlet。一个元素结果的长度属性,powershell,for-loop,cmdlets,Powershell,For Loop,Cmdlets,我使用的Cmdlet可以返回一个或多个元素: PS C:\Users\admin> $x = Get-myObjects PS C:\Users\admin> $x ComputerName : test-2 Description : n/a Id : cbcb1ece-99f5-4478-9f02-65a622df8a98 IsActive

我使用的Cmdlet可以返回一个或多个元素:

PS C:\Users\admin> $x = Get-myObjects
PS C:\Users\admin> $x


ComputerName               : test-2
Description                : n/a
Id                         : cbcb1ece-99f5-4478-9f02-65a622df8a98
IsActive                   :
MinNum                     : 0
Name                       : scom-test2-mp
modeType                   : 1
PSComputerName             :
如果我使用长度属性,我什么也得不到

PS C:\Users\admin> $x.length
PS C:\Users\admin>
但是,如果
Get myObjects
cmdlet返回2个或更多,则它是一个集合,我可以获取
.length
属性


如果get-myObjects cmdlet为一个对象值返回一个对象,如何使.length生效?

我注意到,在这种情况下,最好使用powershell的
foreach
循环

例如:

foreach($i in $x)
{
  Write-Host $i.Name
}

当$x有一个或多个元素时,上述示例适用于这两种情况。

在将cmdlet的返回值分配给变量时,您始终可以将结果强制放入数组:

$x = @(Get-myObjects)
$x.Length
或“按需”:


使用
Measure-Object
cmdlet。这里有点笨重,因为你不能用一种优雅的方式得到伯爵

$x = Get-myObjects
$x | measure-object
输出:

计数:1
平均值:
总和:
最大值:
最小值:
财产:

如果您只想知道计数:

$x | measure-object | select -ExpandProperty Count
输出:

一,


我会选择
$x=@(获取myobjects)
,它可以确保您总是立即获得一个数组,并且以后不必关心它。我喜欢这个解决方案,尤其是第一个选项<代码>$x=@(获取myObjects)另外,这是否特定于PS版本?它是否适用于所有版本的powershell?它至少适用于v2和v3。不确定v1,因为我已经有一段时间没用了。你得到的三个答案都很好。我只想添加一点信息:您的代码与PowerShell3中的代码一样工作
$x | measure-object | select -ExpandProperty Count