3

Powershell スクリプト (ps1 ファイル) を生成するために、VS2010、C#、.NET 3.5 を使用します。

次に、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

もう 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 に答える