8

So I've got a UNC path like so:

\\server\folder

I want to get just the path to server, eg \\server. Split-Path "\\server\folder" -Parent returns "". Anything I try which deals with the root, fails. For example, Get-Item "\\server" fails too.

How can I safely get the path of \\server from \\server\\folder in PowerShell?

jpaugh
  • 6,634
  • 4
  • 38
  • 90
mamidon
  • 895
  • 1
  • 10
  • 25

3 Answers3

17

By using the System.Uri class and querying its host property:

$uri = new-object System.Uri("\\server\folder")
$uri.host # add "\\" in front to get exactly what you asked

Note: For a UNC path, the root directory is the servername plus the share name part.

jon Z
  • 15,838
  • 1
  • 33
  • 35
2

An example using regular expressions:

'\\server\share' -replace '(?<!\\)\\\w+'
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
0
$fullpath = "\\server\folder"
$parentpath = "\\" + [string]::join("\",$fullpath.Split("\")[2])
$parentpath 
\\server
Mitul
  • 9,734
  • 4
  • 43
  • 60
  • $parentPath = "\\" + [string]::join("\",$fullPath.Split("\")[2..3]) –  Mar 05 '18 at 17:51