I have a problem converting UNC location to local drive in powershell. So my code basically takes input from user as read Host as UNC path for a DB Backup location. The location could be like this \\ServerName\m$\SQLBackups\123
.
It then prompts where the backup is being copied from. Again this is a UNC path such as \\ServerName\g$\SQLRestores\444\Filename.bak
.
I need to convert both paths to their local path so that it reads m:\sqldbackups\123
and g:\sqlrestores\444\Filename.bak
.
Here is my code below and I have added a comment of what I want the final output to be.
$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
Split-Path
won't work unless the path is to a directory or file at the root of the share.
Use Path.GetPathRoot()
instead to get the host and share name:
$Drive = [System.IO.Path]::GetPathRoot($BackupPath)
$Dumps = $BackupPath.Substring($Drive.Length)
$Drive = $Drive.Substring($Drive.LastIndexOf('\') + 1).Replace('$',':')
$NTFSPath = "$Drive$Dumps"
I think the answer above is the correct way to do it, but still, sometimes simple pattern matching might be enough:
"\\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)" }
# -replace operator with regex does the trick
PS C:\> '\\ServerName\m$\SQLBackups\123' -replace '(?:.+)\\([a-z])\$\\','$1:\'
m:\SQLBackups\123
来源:https://stackoverflow.com/questions/48901884/convert-unc-path-to-ntfs-local-path