I am trying to perform some simple if statements, but all of the newer cmdlets that are based upon [Microsoft.Management.Infrastructure.CimInstance] don't seem to expose a .count method?
$Disks = Get-Disk
$Disks.Count
Doesn't return anything. I found that I can cast this as an [array], which makes it returns a .NET .count method as expected.
[Array]$Disks = Get-Disk
$Disks.Count
This works without directly casting it as an array for previous cmdlets:
(Get-Services).Count
What is the recommended way to get around this?
An example that doesn't work:
$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 }
Option A (Cast as Array):
[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 }
Option B (Use Array Indexes):
$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 }
Option C (Array) -Thanks to @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 }
What is the reason for CIM based cmdlets not exposing the .Count method? What is the recommended way to handle this? Option B seems convoluted to me, and hard to read. Option A works, but shouldn't powershell cast this as an array for me? Am I going about this in entirely the wrong way?
$Result = @(Your command here)(Get-Services).Countworks becauseGet-Servicesreturns multiple objects. If you need an array (of potentially 0 or 1 object(s)), then use the array sub-expression operator (@(...)) as suggested by @PetSerAl above[Array]$a = &{}; $b = @(&{}); $a.GetType(); $b.GetType()or[Array]$a = New-Object Object[] 10; $b = @(New-Object Object[] 10); $a.Count; $b.Countor[Array]$a = New-Object Collections.Generic.List[Object]; $b = @(New-Object Collections.Generic.List[Object]); $a.Count; $b.Count.