Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only the drive letter from a path in PowerShell

Tags:

powershell

I want to make a script in PowerShell to help easily translate a path like this:

H:\MyDoc.docx

Into its true absolute path, like this:

\\FileServer\UserShares\Organization\Department\Me\MyDoc.docx

In this case, I've created a network drive mapping on my local computer that points H:\ to \\FileServer\UserShares\Organization\Department\Me\, but I need to easily expand the mapped path in order to share it with other users who may not have the drive mapping.

Getting the path for the drive is easy.

(Get-PSDrive H).DisplayRoot

However, I encounter a problem when I try write a more generic script that can automatically adapt to paths which might point to other mapped drives (I do have several). What I'm having a hard time figuring out is how to extract just the drive letter from a given path.

I thought Split-Path would help, but it appears to only be able to pull the path apart in chunks - the "Parent" and the "Leaf" - neither of which will give only the drive letter.

Is there a way to get just the drive letter from a given path in PowerShell?

Note: I need this to work for paths that point to files or folders.

like image 755
Iszi Avatar asked Mar 10 '15 14:03

Iszi


2 Answers

As of PowerShell 3.0, Split-Path now offers the -Qualifier option:

-Qualifier
   Indicates that this cmdlet returns only the qualifier of the specified path.
   For the FileSystem or registry providers, the qualifier is the drive of the
   provider path, such as C: or HKCU:.

Using OP's example:

PS C:\> Split-Path -Path "H:\MyDoc.docx" -Qualifier

returns H:

like image 164
Sam C Avatar answered Nov 20 '22 08:11

Sam C


You could use the PSDrive property of the FileInfo object:

(Get-Item .\your\path\to\file.ext).PSDrive.Name
like image 34
arco444 Avatar answered Nov 20 '22 06:11

arco444