【问题标题】:Escape characters when generating Powershell scripts using C#使用 C# 生成 Powershell 脚本时转义字符
【发布时间】:2013-03-06 10:43:17
【问题描述】:

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

【问题讨论】:

    标签: c# powershell escaping stringescapeutils


    【解决方案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 不将它们用作转义字符。这使得编写正则表达式更加容易。

    【讨论】:

    • 也许正则表达式是"['\"]"?需要转义多余的"
    • @C.B.请注意文字字符串 (@"…") 的使用:您可以通过将文字字符串中的双引号加倍来转义它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    相关资源
    最近更新 更多