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.
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:
You could use the PSDrive
property of the FileInfo object:
(Get-Item .\your\path\to\file.ext).PSDrive.Name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With