powershellenumerationmember-enumeration

Powershell command to get filesystem drive names - member-access enumeration


I am trying to fetch disk free space and used space in windows 2008 R2 enterprise edition. However the command fails to get the values. This command works fine in windows 2012 version.

Get-PSDrive -PSProvider FileSystem will fetch below details..

Name Used (GB) Free (GB) Provider ---- --------- --------- -------- C 71.99 166.23 FileSystem H 71.99 166.23 FileSystem

(Get-PSDrive -PSProvider FileSystem).Name - get me the drive names and so I use to fetch the other details.

However the same command does not work for windows 2008 R2 enterprise edition. Any work around for this ?


Solution

  • (Get-PSDrive -PSProvider FileSystem).Name relies on member-access enumeration, a feature that was introduced in PSv3, whereas Windows Server 2008 R2 ships with PSv2.

    Member-access enumeration means that you can access a property such as .Name on a collection (array) and have that property implicitly accessed on each element of that collection, with the results collected in an array.

    In PSv2-, you must use the ForEach-Object cmdlet (or its alias, %) instead:

    Get-PSDrive -PSProvider FileSystem | % { $_.Name } # return drive names as array