Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

An example using regular expressions:

'\\server\share' -replace '(?<!\\)\\\w+'
$fullpath = "\\server\folder"
$parentpath = "\\" + [string]::join("\",$fullpath.Split("\")[2])
$parentpath 
\\server
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top