Escape characters when generating Powershell scripts using C#

二次信任 提交于 2019-12-20 01:38:34

问题


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:


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.



来源:https://stackoverflow.com/questions/15245119/escape-characters-when-generating-powershell-scripts-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!