How to get list of drive letters in Powershell 2.0
18,033
Solution 1
Get-PSDrive
This will return all drives mapped in the current session. The Name
property contains the drive letter.
To capture just drive letters:
(Get-PSDrive).Name -match '^[a-z]$'
Tested working in PSv2:
Get-PSDrive | Select-Object -ExpandProperty 'Name' | Select-String -Pattern '^[a-z]$'
Solution 2
$drives = (Get-PSDrive -PSProvider FileSystem).Root
returns an array for drives with the root path:
C:\
D:\
E:\
You can easily trim the ending if you don't want it.
Author by
sloppyfrenzy
Updated on June 28, 2022Comments
-
sloppyfrenzy almost 2 years
I'm trying to get a list of drive letters in a drop-down menu. I'm currently using the code below and it works just fine in Windows 10, but doesn't work at all in Windows 7.
$Drive_Letters = Get-WmiObject Win32_LogicalDisk ForEach ($Drives in $Drive_Letters.DeviceID) { $Dest_Drive_Box.Items.Add($Drives) }
In Win 7 I tried adjusting the code to this...
$Drive_Letters = Get-WmiObject Win32_LogicalDisk | Select-Object DeviceID ForEach ($Drives in $Drive_Letters) { $Dest_Drive_Box.Items.Add($Drives) }
But now it shows "@DeviceID=C:}", "@DeviceID=D:}", etc. in Win 7 and 10 for each drive letter. I need to just show "C:", "D:", etc.
Thanks!