Powershell: find / replace ASCII control character pattern

I am trying to write a script to search for the contents of a file, and when it encounters a grouping of ASCII control characters to insert CR / LF.

The character pattern that I would like to replace is [ETX] [NUL] [STX] [ETX] [SOH]

    $ filenames = @ (Get-Childitem "E: \ VendorFiles \ *")

    $ CR = @ ("[char] 3 [char] 0 [char] 2 [char] 3 [char] 1")
    foreach ($ file in $ filenames) {$ outfile = "$ file" + ".txt"
    Get-Content $ file | Foreach-object {
            $ _ -replace $ CR, "` r`n "`
             -replace [char] 3, "|" `
             -replace [char] 1, "{" `
             -replace "\\", "\\" `
        } | Set-Content -encoding "UTF8" $ outfile}
+5
source share
3 answers

This expression:

@("[char]3 [char]0 [char]2 [char]3 [char]1")

... creates an array with one element. You need commas between terms if you really want an array of 5 elements but -replacedon't support arrays anyway. In addition, your only element contains the literal characters you typed; not what you expected.

You need to create a simple string to feed to -replace; this is a little more important when dealing with non-printable characters. You had the right idea - you just need to tell PowerShell to interpolate the code expressions inside your string using the notation $()for each expression:

$CR = "$([char]3)$([char]0)$([char]2)$([char]3)$([char]1)"
+6
source

.

:

$CR = ([char[]] (3, 0, 2, 3, 1)) -join ''
  • 3, 0, 2, 3, 1 Unicode .

  • Cast [char[]] ([char]).

  • -join '' ( ) .

+1

I have a function in a script that does something like this. Not sure if this will help you:

# This function will make a new file that has custom comments
# it will comment out "rollback tran"
# it will uncomment out "--commit tran"
function CommentAndUncomment($TheScript)
{
    PrintTextAndTime("About to run this SQL file: $TheScript")
    PrintTextAndTime("Will comment out 'rollback tran' and uncomment '--commit tran'")
    $content = Get-Content $TheScript
    $content | 
      ForEach-Object { 
        if ($_ -clike "*ROLLBACK TRAN;*") { 
          $_ -replace "ROLLBACK TRAN;", "--ROLLBACK TRAN;"
        } 
        elseif ($_ -clike "*--COMMIT TRAN;*") { 
          $_ -replace "--COMMIT TRAN;", "COMMIT TRAN;"
        }
        else{
            $_
        }
      } | 
      Set-Content $ModifiedCommentsFile
    echo $ModifiedCommentsFile
    sqlcmd -i $ModifiedCommentsFile
    del $ModifiedCommentsFile
}
0
source

All Articles