Replace command not working

Hi,

I am trying to change a string using replace command:

$BackupFolder = 'E:\SQLBackups\MYSQLSRV'
$filename = ‘E:\SQLBackups\MYSQLSRV\Daily\mydb.bak.zip’
$S3filename = $filename -replace ‘$BackupFolder’

$s3Folder = ‘SRVNAME’
$S3filename3 = $filename -replace 'Daily', 'Daily$s3Folder'
$S3filename3

The first replace does nothing, the second returns an error:

The regular expression pattern Daily\ is not valid.
At line:1 char:1
+ $S3filename3 = $filename -replace 'Daily', ‘Daily$s3Folder’
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Daily:String) , RuntimeException
+ FullyQualifiedErrorId : InvalidRegularExpression

All I want to do is to remove the first part of the string and insert $s3Folder value after 'Daily' string.

Any ideas?

Thanks.

 

The -replace operator uses regular expressions. Backslash in regex is an escape character by itself so simply escape it with another backslash to match a single. Take a look at the following example with -match, another operator that uses regex.

'abc\def' -match '\' # error: illegal \ at end of pattern
'abc\def' -match '\\' # true

Now that we understand that, we can make either work as desired. Let’s use your second example.

$filename = 'E:\SQLBackups\MYSQLSRV\Daily\mydb.bak.zip'
$s3Folder = 'SRVNAME'
$S3filename3 = $filename -replace 'Daily\\', 'Daily\$s3Folder\'
$S3filename3  # Now E:\SQLBackups\MYSQLSRV\Daily\$s3Folder\mydb.bak.zip

You can also use [regex]::escape() and it will handle escaping characters that require it.

$BackupFolder = 'E:\SQLBackups\MYSQLSRV\'
$filename = 'E:\SQLBackups\MYSQLSRV\Daily\mydb.bak.zip'
$S3filename = $filename -replace [regex]::Escape("$BackupFolder") # Now Daily\mydb.bak.zip

Note that since it was a variable we had to change the single quotes to double quotes for the variable to expand properly.

Two quick other adds. Single qoutes are literal and will not expand $s3Folder, use double qoutes:

PS C:\Users\rasim> $fileName = 'C:\Daily\FooFah.txt'
$s3Folder = 'SRVNAME'
$S3filename3 = $filename -replace 'Daily\\', 'Daily\$s3Folder\'

$S3filename3
C:\Daily\$s3Folder\FooFah.txt

PS C:\Users\rasim> $fileName = 'C:\Daily\FooFah.txt'
$s3Folder = 'SRVNAME'
$S3filename3 = $filename -replace 'Daily\\', "Daily\$s3Folder\"

$S3filename3
C:\Daily\SRVNAME\FooFah.txt

Next, as Doug mentioned, -replace uses regex, but there is also the string method replace that does not require an escape:

PS C:\Users\rasim> $fileName = 'C:\Daily\FooFah.txt'
$s3Folder = 'SRVNAME'
$S3filename3 = $filename.Replace('Daily\', "Daily\$s3Folder\")

$S3filename3
C:\Daily\SRVNAME\FooFah.txt