3

我使用 VS2010、C#、.NET 3.5 来生成 Powershell 脚本(ps1 文件)。

然后,Powershell 需要转义字符。

关于它开发逃脱字符的好方法有什么建议吗?

  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("'", "`'");
        }
    }

用法:

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

1 回答 1

1

另一种选择是使用正则表达式:

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, "`$&");
}

注意:您不需要转义反斜杠:PowerShell 不将它们用作转义字符。这使得编写正则表达式更加容易。

于 2013-03-06T11:26:44.500 回答