我使用 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/