regexpowershellescapingspecial-characters

Does there exists a PowerShell Escape function for Special Characters


Does there exists a PowerShell Escape function to replace control characters (as e.g. a carriage return) with Special PowerShell Characters?
(Similar to the Regex.Escape(String) Method for escaping special regex characters)
Or is there a smarter way to do this than the self-answer?
(I am less concerned with the Unicode escape sequence: `u{x})


Solution

  • Using a regular expression callback:

    $Backtick = @{}
    foreach ($Char in '0abefnrtv`'.ToCharArray()) {
        $Backtick[$ExecutionContext.InvokeCommand.ExpandString("``$Char")] = "``$Char"
    }
    $SpecialCharacters = '[' + (-Join $Backtick.get_Keys()) + ']'
    function Escape($Text) {
        [regex]::Replace($Text, $SpecialCharacters, { param($Match) $Backtick[$Match.Value] })
    }
    

    Escape 'Test
    123'
    
    Test`n123