2013-03-06 54 views
3

我使用VS2010,C#,.NET 3.5生成Powershell脚本(ps1文件)。使用C#生成Powershell脚本时转义字符

然后,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 + "\";"; 

回答

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不把它们作为转义字符。这使得编写正则表达式更容易一些。

+0

也许正则表达式是''['\“]”'?需要转义额外的'“' – 2013-03-06 11:39:01

+0

@ C.B。请注意使用文字字符串('@“...”'):通过使文字字符串中的双引号加倍来避免双引号。 – Richard 2013-03-06 11:41:54