将UNC路径转换为NTFS本地路径

问题描述 投票:0回答:3

我在使用powershell将UNC位置转换为本地驱动器时遇到问题。因此,我的代码基本上将来自用户的输入作为读取主机作为数据库备份位置的UNC路径。位置可能像这个\\ServerName\m$\SQLBackups\123

然后它会提示从中复制备份的位置。这又是一个UNC路径,如\\ServerName\g$\SQLRestores\444\Filename.bak

我需要将两个路径转换为它们的本地路径,以便它读取m:\sqldbackups\123g:\sqlrestores\444\Filename.bak

这是我下面的代码,我添加了一个关于我想要最终输出的注释。

$BackupPath = "\\ServerName\m$\SQLBackups\123"
$Dumps = Split-Path -Path $BackupPath -Leaf
$Drive = Split-Path -Path $BackupPath -Parent
$LastTwo = $Drive.Substring($Drive.get_Length()-2)


$FullNTFS = $LastTwo + "\" + $Dumps
$FullNTFS = $FullNTFS.Replace("$",":")
$FullNTFS 
#This should be M:\SQLBACKUPS\123

$RestorePath = "\\ServerName\g$\SQLRestores\444\Filename.bak"
$Dumps = Split-Path -Path $RestorePath -Leaf
$Drive = Split-Path -Path $RestorePath -Parent
$LastTwo = $Drive.Substring($Drive.get_Length()-2)


$FullNTFS = $LastTwo + "\" + $Dumps
$FullNTFS = $FullNTFS.Replace("$",":")
$FullNTFS 
#This should be read as g:\sqlrestores\444\FileName.bak
powershell powershell-v3.0
3个回答
6
投票

除非路径指向共享根目录或文件,否则Split-Path将无法工作。

使用Path.GetPathRoot()来获取主机和共享名称:

$Drive = [System.IO.Path]::GetPathRoot($BackupPath)
$Dumps = $BackupPath.Substring($Drive.Length)
$Drive = $Drive.Substring($Drive.LastIndexOf('\') + 1).Replace('$',':')
$NTFSPath = "$Drive$Dumps"

0
投票

我认为上面的答案是正确的方法,但有时简单的模式匹配可能就足够了:

"\\server2.net\g$\foo\bar\baz", "\\server1.com\c$\baz\bar\foo" |
Select-String -Pattern "([A-z])\`$(.*)" |
%{ "$($_.Matches.Groups[1].value):$($_.Matches.Groups[2].value)" }

0
投票
# -replace operator with regex does the trick
PS C:\> '\\ServerName\m$\SQLBackups\123' -replace '(?:.+)\\([a-z])\$\\','$1:\'
m:\SQLBackups\123
© www.soinside.com 2019 - 2024. All rights reserved.