3

I use VS2010, C#, .NET 3.5 for generate Powershell scripts (ps1 files).

Then, it is required escape characters for Powershell.

Any suggestions about it for develop good method that escape characters?

  public static partial class StringExtensions
    {
        /*
        PowerShell Special Escape Sequences

        Escape Sequence         Special Character
        `n                      New line
        `r                      Carriage Return
        `t                      Tab
        `a                      Alert
        `b                      Backspace
        `"                      Double Quote
        `'                      Single Quote
        ``                      Back Quote
        `0                      Null
        */

        public static string FormatStringValueForPS(this string value)
        {
            if (value == null) return value;
            return value.Replace("\"", "`\"").Replace("'", "`'");
        }
    }

Usage:

var valueForPs1 = FormatStringValueForPS("My text with \"double quotes\". More Text");
var psString = "$value = \"" + valueForPs1  + "\";";

1 Answer 1

1

The other option would be to use a regex:

private static Regex CharactersToEscape = new Regex(@"['""]"); // Extend the character set as requird


public string EscapeForPowerShell(string input) {
  // $& is the characters that were matched
  return CharactersToEscape.Replace(input, "`$&");
}

Note: you don't need to escape backslashes: PowerShell does not use them as escape characters. This makes writing regexes somewhat easier.

Sign up to request clarification or add additional context in comments.

2 Comments

maybe the regex is "['\"]"? need to escape the extra "
@C.B. Note the use of a literal string (@"…"): you escape double quotes in a literal string by doubling them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.