【问题标题】:Split-Path with Root UNC Directory具有根 UNC 目录的拆分路径
【发布时间】:2013-08-24 06:07:09
【问题描述】:

所以我有一个像这样的 UNC 路径:

\\server\folder

我只想获取服务器的路径,例如\\serverSplit-Path "\\server\folder" -Parent 返回""。我尝试的任何处理根的方法都失败了。 例如,Get-Item "\\server" 也会失败。

如何在 PowerShell 中安全地从 \\server\\folder 获取 \\server 的路径?

【问题讨论】:

  • 这个服务器故障帖子有用吗? serverfault.com/questions/297690/…
  • 并非如此,Split-Path 等适用于“\\server\folder1\folder2”形式的路径
  • 对于 UNC 路径,根目录是服务器名 + 共享名。

标签: string powershell path unc


【解决方案1】:

通过使用System.Uri 类并查询其host 属性:

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

注意:对于 UNC 路径,根目录是服务器名加上共享名部分。

【讨论】:

  • 我喜欢在 New-Object 上使用 URI 类型进行转换,但是 +1 $URI = [URI]"\\Server\Folder" $URI.Host
【解决方案2】:

一个使用正则表达式的例子:

'\\server\share' -replace '(?<!\\)\\\w+'

【讨论】:

    【解决方案3】:
    $fullpath = "\\server\folder"
    $parentpath = "\\" + [string]::join("\",$fullpath.Split("\")[2])
    $parentpath 
    \\server
    

    【讨论】:

    • $parentPath = "\\" + [string]::join("\",$fullPath.Split("\")[2..3])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2016-06-02
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多