Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of drive letters in Powershell 2.0

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!

like image 412
sloppyfrenzy Avatar asked Aug 30 '17 16:08

sloppyfrenzy


2 Answers

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]$'
like image 131
Maximilian Burszley Avatar answered Oct 25 '22 13:10

Maximilian Burszley


$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.

like image 24
Joe B Avatar answered Oct 25 '22 15:10

Joe B