【问题标题】:Get ShareName from UNC Path从 UNC 路径获取 ShareName
【发布时间】:2018-08-28 09:13:27
【问题描述】:

我正在执行一项任务,我需要从 UNC 路径获取服务器上的本地路径。

基本上\\server\MyShare\Somewhere\Bla 应该是例如D:\foo\bar\somewhere\bla

我从[system.Uri]$Path 知道服务器主机,所以我知道在哪个服务器中查找本地路径

我可以使用Get-SmbShare 获取服务器上的共享。

我现在唯一需要比较两者的就是拆分 UNC 路径并获取共享名。

有没有简单的方法可以做到这一点? -split '\' 不起作用。

我希望最后有一个数组,我可以选择[1]。任何其他方法也非常受欢迎。

【问题讨论】:

  • ("\\server\MyShare\Somewhere\Bla" -split '\\')[3] 返回MyShare 拆分运算符是基于正则表达式的,因此您需要用另一个反斜杠转义。
  • this 答案。如果它是相关的!
  • 非常感谢你们!

标签: powershell


【解决方案1】:

对于$list 类型为[System.URI] 类型的值,您可以:

   $result=@()
    Foreach ($uri in $list)
    {
    $object =""|select URI,Hostname,Localpath 
        $object.uri=$uri.LocalPath
        $object.hostname=$uri.Authority
        $object.LocalPath= Invoke-Command -ComputerName $($uri.Authority) -ScriptBlock {param ($uri) (Get-SmbShare ($uri.AbsolutePath -split '/')[1]).path} -ArgumentList $uri
    $result+=$object
    }
$result

【讨论】:

    【解决方案2】:

    你可以像这样拆分 unc 路径:

    $uncPath = '\\server\MyShare\Somewhere\Bla'
    $server, $share, $remainingPath = ($uncPath -replace '^\\+', '').Split("\", 3)
    

    然后,使用 WMI 获取共享的本地路径:

    $localShare = Get-WmiObject win32_share -ComputerName $server | Where-Object {$_.Name -eq $share} | Select-Object -ExpandProperty Path
    

    或使用 Get-SmbShare cmdlet:

    $localShare = Get-SmbShare -Name $server | Where-Object {$_.Name -eq $share} | Select-Object -ExpandProperty Path
    

    将此 $localShare 与您之前从拆分中获得的 $remainingPath 结合起来,您将获得完整的本地路径

    $localPath = Join-Path $localShare $remainingPath
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多