Split path with UNC root directory

So, I have a UNC path something like this:

\\server\folder 

I want to get only the path to the server, for example, \\server . Split-Path "\\server\folder" -Parent returns "" . Everything that I try, as for the root, does not produce results. For example, Get-Item "\\server" does not work either.

How to safely get the path to \\server from \\server\\folder in PowerShell?

+5
source share
3 answers

Using the System.Uri class and requesting its host property:

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

Note. For the UNC path, the root directory is the server name and part of the common name.

+11
source

An example of using regular expressions:

 '\\server\share' -replace '(?<!\\)\\\w+' 
+2
source
 $fullpath = "\\server\folder" $parentpath = "\\" + [string]::join("\",$fullpath.Split("\")[2]) $parentpath \\server 
0
source

Source: https://habr.com/ru/post/1498252/


All Articles