Gordon
Gordon

Reputation: 6863

Get Path root (local, mapped network drive or UNC)

Split-Path will easily get just the file name with -leaf, or just the full parent path with -parent, or just the root with -qualifier, but only if the path is a local path. But, is there an easy way to get the root of a path, be it a local drive letter, mapped drive letter or UNC? Basically what one would expect from Split-Path $path -root.

To provide some context, I am logging information and I want to provide the parent and target, so Fonts\arial.ttf for C:\Windows\Fonts\arial.ttf. But, if the parent is the first child of the root, then show the whole path, so I don't want Windows\Fonts for C:\Windows\Fonts. I have the logic for doing this, I just need to get the root so I can determine if the parent of the parent is root or not. However, getting root seems to be a lot of work depending on which condition applies. No doubt there is a regEx approach that works, but I wonder if there is a native PowerShell or .NET approach that avoids the pitfalls of RegEx?

Upvotes: 2

Views: 4265

Answers (1)

Matt
Matt

Reputation: 46680

The simplest thing you could use for this is

[System.IO.path]::GetPathRoot($path)

It works for UNC paths, network drives and local drives. It does not work will all providers though. Registry for example would not work.

PS M:\> [System.IO.path]::GetPathRoot("C:\temp")
C:\

PS M:\> [System.IO.path]::GetPathRoot("hklm:\temp")


PS M:\> [System.IO.path]::GetPathRoot("\\s5000\Software\Windows\win.ini")
\\s5000\Software

PS M:\> [System.IO.path]::GetPathRoot("M:\DRAFT.docx")
M:\

Upvotes: 5

Related Questions