I have the following script that gets the default log and data locations for an SQL server:
$Server = '.\DEV_MIGRATIONS'
$SMOServer = new-object ('Microsoft.SqlServer.Management.Smo.Server') $Server
# Get the Default File Locations
### Get log and data locations
$DefaultFileLocation = $SMOServer.Settings.DefaultFile
$DefaultLogLocation = $SMOServer.Settings.DefaultLog
if ($DefaultFileLocation.Length -eq 0) { $DefaultFileLocation = $SMOServer.Information.MasterDBPath }
if ($DefaultLogLocation.Length -eq 0) { $DefaultLogLocation = $SMOServer.Information.MasterDBLogPath }
$Schema_DataLocation = ($DefaultFileLocation + "Test.mdf")
$Schema_DataLocation
[Regex]::Escape($Schema_DataLocation)
I am trying to use the $Schema_DataLocation
in a replace function for a schema creation script but i get errors when trying to replace the path which requires escaping regex.
What i get from the [Regex]::Escape
call is:
C:\\Program\ Files\\Microsoft\ SQL\ Server\\MSSQL14\.DEV_MIGRATIONS\\MSSQL\\DATA\\Test\.mdf
instead of:
C:\Program Files\Microsoft SQL Server\MSSQL14.DEV_MIGRATIONS\MSSQL\DATA\Test.mdf
the replace commands:
(Get-Content $Script_SchemaCreate) |
Foreach-Object { $_ -replace "DFILEPATH", $Schema_DataLocation } |
Set-Content $Script_SchemaCreate
(Get-Content $Script_SchemaCreate) |
Foreach-Object { $_ -replace [Regex]::Escape($Schema_DataLocation), "DFILEPATH" } |
Set-Content $Script_SchemaCreate
The first replace works, but the second fails because it is trying to match a different value.
Removing [Regex]::Escape
i get the following error:
The regular expression pattern C:\Program Files\Microsoft SQL Server\MSSQL14.DEV_MIGRATIONS\MSSQL\DATA\Migration_Data.mdf is not valid.