Monthly Archive


W2KSG: Using Collections

As we saw in the previous post Get-WMIObject returns a collection of objects. To continue with our script development to take that into account.

PowerShell handles objects on the pipeline so we don't need to use the collection explicitly

Listing 2.8 would become

## listing 2.8

$convert = 1MB
$computer = "pcrs2"

Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk | Format-Table DeviceID, @{Label="FreeSpace(MB)";Expression={[int]($_.Freespace/$convert)}} -AutoSize

If you need to iterate through the results you would use foreach

Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk | ForEach-Object {

Write-Host "There are $([int]($_.Freespace/$convert)) megabytes of free disk space on $($_.DeviceID)"


Alternatively you could generate the collection and then iterate

## iterate through results collection
$disks = Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk

foreach ($disk in $disks) {

Write-Host "There are $([int]($disk.Freespace/$convert)) megabytes of free disk space on $($disk.DeviceID)"


This is closer to the VBScript approach and for very large collections may well be faster. The drawback to this approach is  is that you generate the objects and then work with them. Foreach-Object works on the pipeline as the objects appear.

If a collection is empty the Foreach-Object approach will just return nothing - not sure if it worked or not. To test if the results are empty use this

## test for empty collection
$tapes = Get-WmiObject -Class Win32_TapeDrive
if ($tapes -eq $null){Write-Host "No tape drives installed"}
else {    foreach ($tape in $tapes) {$tape.Name}}

We can't test for a collection with zero members as we do with VBScript so we have to test for the collection being null.


Share this post :

Technorati Tags: PowerShell

Leave a Reply