使用C#生成Powershell的脚本时转义字符(Escape characters when ge

2019-07-21 01:42发布

我用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  + "\";";

Answer 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不会将它们作为转义字符。 这使得书写的正则表达式比较容易。



文章来源: Escape characters when generating Powershell scripts using C#