我正试图执行一些简单的if语句,但是所有基于[Microsoft.Management.Infrastructure.CimInstance]的新命令都似乎没有暴露.count方法?
$Disks = Get-Disk
$Disks.Count
没有任何返回值。我发现可以将它转换为[array],这样就像预期那样返回了.NET .count方法。
[Array]$Disks = Get-Disk
$Disks.Count
这个命令可以在不直接将其转换为数组的情况下正常工作:
(Get-Services).Count
什么是推荐的解决方法?
一个不起作用的例子:
$PageDisk = Get-Disk | Where {($_.IsBoot -eq $False) -and ($_.IsSystem -eq $False)}
If ($PageDisk.Count -lt 1) {Write-Host "No suitable drives."; Continue}
Else If ($PageDisk.Count -gt 1) {Write-Host "Too many drives found, manually select it."}
Else If ($PageDisk.Count -eq 1) { Do X }
选项 A(强制转换为数组):
[Array]$PageDisk = Get-Disk | Where {($_.IsBoot -eq $False) -and ($_.IsSystem -eq $False)}
If ($PageDisk.Count -lt 1) {Write-Host "No suitable drives."; Continue}
Else If ($PageDisk.Count -gt 1) {Write-Host "Too many drives found, manually select it."}
Else If ($PageDisk.Count -eq 1) { Do X }
选项B(使用数组索引):
$PageDisk = Get-Disk | Where {($_.IsBoot -eq $False) -and ($_.IsSystem -eq $False)}
If ($PageDisk[0] -eq $Null) {Write-Host "No suitable drives."; Continue}
Else If ($PageDisk[1] -ne $Null) {Write-Host "Too many drives found, manually select it."}
Else If (($PageDisk[0] -ne $Null) -and (PageDisk[1] -eq $Null)) { Do X }
选项 C(数组)- 感谢 @PetSerAl:
$PageDisk = @(Get-Disk | Where {($_.IsBoot -eq $False) -and ($_.IsSystem -eq $False)})
If ($PageDisk.Count -lt 1) {Write-Host "No suitable drives."; Continue}
Else If ($PageDisk.Count -gt 1) {Write-Host "Too many drives found, manually select it."}
Else If ($PageDisk.Count -eq 1) { Do X }
CIM基于cmdlets为什么不公开.Count方法?应该如何处理?选项B似乎很复杂,难以阅读。选项A可行,但PowerShell不应该将其强制转换为数组吗?我的做法完全错了吗?
$Result = @(Your command here)
- user4003407(Get-Services).Count
的工作原理是因为Get-Services
返回多个对象。如果需要一个数组(可能包含0或1个对象),则可以使用数组子表达式运算符(@(...)
),正如 @PetSerAl 上面建议的那样。 - Mathias R. Jessen[Array]$a = &{}; $b = @(&{}); $a.GetType(); $b.GetType()
或[Array]$a = New-Object Object[] 10; $b = @(New-Object Object[] 10); $a.Count; $b.Count
或[Array]$a = New-Object Collections.Generic.List[Object]; $b = @(New-Object Collections.Generic.List[Object]); $a.Count; $b.Count
。 - user4003407