How to split parent path of a unc path by using powershell?

Solution 1:

There are a few options. If you have access to the share then:

(Get-Item '\\sharespace\test1\10.0.1212.1').Parent.Fullname

If you do not have access to the share, you can go the more unpalatable route of manipulating the string in various ways. This is one:

$path = '\\sharespace\test1\10.0.1212.1'
[string]::Join('\', $path.Split('\')[0..$($path.Split('\').Length-2)])

Solution 2:

There's a cmdlet for this:

Split-Path \\sharespace\test1\10.0.1212.1
\\sharespace\test1

It doesn't include the trailing '\', but if you use Join-Path then PowerShell will take care of adding it if required anyway.

NOTE: Split-Path and Join-Path try to resolve the path on the local machine, so if the path has a drive letter (say, 'F:') that is not a valid drive on the local machine, these cmdlets will throw an error. With UNC paths like the above you shouldn't have a problem.

Tags:

Powershell