c# - 使用 C# 生成 Powershell 脚本时转义字符

标签 c# powershell escaping stringescapeutils

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

最佳答案

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

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# - 使用 C# 生成 Powershell 脚本时转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15245119/

相关文章:

javascript - 正则表达式匹配美元,前面没有反斜杠

java - 为什么转义字符不能用于替换所有括号?

c# - 快速从数据表中删除在另一个数据表中找不到的行

c# - 如何将计算值添加到此 TryUpdateModelAsync<>

powershell - 如何验证 PowerShell 函数参数是否允许空字符串?

powershell - 在 PowerShell 7.2 中更改详细颜色

powershell - 尝试将变量传递到 [adsisearcher] 的问题

php - 转义 urldecode 转义混淆

c# - 从 .net 客户端访问 ssl 服务器(web 服务)

c# - 复杂类型的子集和