我使用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 + "\";";
答案 0 :(得分: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不会将它们用作转义字符。这使得编写正则表达式更容易一些。