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

时间:2018-02-21 09:07:59

标签: powershell powershell-v3.0

我在使用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

3 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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)" }

答案 2 :(得分:0)

# -replace operator with regex does the trick
PS C:\> '\\ServerName\m$\SQLBackups\123' -replace '(?:.+)\\([a-z])\$\\','$1:\'
m:\SQLBackups\123