Replace command not working

Welcome Forums General PowerShell Q&A Replace command not working

Viewing 2 reply threads
  • Author
    • #262010
      Topics: 12
      Replies: 17
      Points: 56
      Rank: Member


      I am trying to change a string using replace command:

      $BackupFolder = 'E:\SQLBackups\MYSQLSRV\'
      $filename = 'E:\SQLBackups\MYSQLSRV\Daily\'
      $S3filename = $filename -replace '$BackupFolder'

      $s3Folder = 'SRVNAME'
      $S3filename3 = $filename -replace 'Daily\', 'Daily\$s3Folder\'

      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?



    • #262016
      Topics: 8
      Replies: 617
      Points: 2,393
      Helping Hand
      Rank: Community Hero

      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.

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

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

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

    • #262226
      Topics: 16
      Replies: 1794
      Points: 3,300
      Helping Hand
      Rank: Community Hero

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

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

Viewing 2 reply threads
  • You must be logged in to reply to this topic.