avi
avi

Reputation: 1846

Powershell get a list of drives

I'm using this command to get a list of my drives in my Windows:

get-wmiobject win32_volume | ? { $_.DriveType -eq 3 } | % { get-psdrive $_.DriveLetter[0] }

This gives:

Name           Used (GB)     Free (GB) Provider      Root
----           ---------     --------- --------      ----
C                 131.85        333.62 FileSystem    C:\
D                 111.15        200.63 FileSystem    D:\

What I actually want to get is the list of values under "Root" column. Basically a string as follows C:\ D:\

How can I do that?

EDIT:

I Managed to do this:

get-wmiobject win32_volume | ? { $_.DriveType -eq 3 } | % { get-psdrive $_.DriveLetter[0] } | Select Root

Which Gives:

   Root
   ----
   C:\
   D:\

How do I convert it to:

 C:\ D:\

Upvotes: 1

Views: 4511

Answers (2)

iRon
iRon

Reputation: 23613

To prevent errors like:

Cannot index into a null array.
At line:1 char:82
+ ...  3 } | % {$_.DriveLetter} | % { get-psdrive $_.DriveLetter[0] } | Sel ...
+                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

I would include -and $_.DriveLetter in the Where clause.

And I think that there is no need to use Get-PSDrive as the required output is already available in the Name.

Thus:

get-wmiobject win32_volume | ? {$_.DriveType -eq 3 -and $_.DriveLetter} | Select -Expand Name

Upvotes: 3

Ranadip Dutta
Ranadip Dutta

Reputation: 9123

try this:

(get-wmiobject win32_volume | ? { $_.DriveType -eq 3 } | % { get-psdrive $_.DriveLetter[0] }).Root

It will show line by line like:

C:\
D:\

Else you can do like this to get it side by side:

(get-wmiobject win32_volume | ? { $_.DriveType -eq 3 } | % { get-psdrive $_.DriveLetter[0] }).Root -join " "

It will output like this:

C:\ D:\

Hope it helps.

Upvotes: 3

Related Questions