2013-03-06 1 views
3

Powershell 스크립트 (ps1 파일)를 생성하기 위해 VS2010, C#, .NET 3.5를 사용합니다.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

어쩌면 정규식은''[ '\ "]"'? 여분의'''' –

+0

@ C.B를 이스케이프해야합니다. 리터럴 문자열 ('@ "..."')의 사용에주의하십시오 : 리터럴 문자열에서 이중 따옴표를 두 배로 이스케이프 처리합니다. – Richard