0
votes

I need to write script to iterate through all drives available in system and then do something with those drives. The code need to support PS versions 2.0 – 4.0. Problem is that when I retrieve list of drives, it comes back with different types between PS version 2.0 and 4.0 as shown below.

$PSVersionTable
$drives = Get-WmiObject -class Win32_LogicalDisk -Filter "DriveType=3" | select   Name  
'Type = ' + $drives.GetType().FullName
Foreach($drive in $drives)
{
    #some logic
}

Here is output in PS version 2.0

Name Value

---- ----- CLRVersion 2.0.50727.5485
BuildVersion 6.1.7601.17514
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
Type is System.Management.Automation.PSCustomObject

This is what I get in PS version 3.0 and above.

Name Value
---- ----- PSVersion 4.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.42000
BuildVersion 6.3.9600.16394
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion 2.2
Type is System.Object[]

How can I make PS version 2.0 to also return an object[] so that my code could be consistent

1

1 Answers

2
votes

It returns a single PSCustomObject-object because there only is one logical disk that matches your criteria on your Win7 (PS 2.0) computer. On your Win8.1 computer (PS 4.0) you have multiple disks that matches which is why you get an array.

You can wrap any result in an array using the array operator @() to make sure you always get an array (even with zero items).

$drives = @(Get-WmiObject -class Win32_LogicalDisk -Filter "DriveType=3" | select Name)