Escape characters when creating Powershell scripts using C #

I am using VS2010, C #, .NET 3.5 to generate Powershell scripts (ps1 files).

Then Powershell requires escape characters.

Any suggestions on this to develop a good method that avoids characters?

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("'", "`'"); } } 

Using:

 var valueForPs1 = FormatStringValueForPS("My text with \"double quotes\". More Text"); var psString = "$value = \"" + valueForPs1 + "\";"; 
+3
source share
1 answer

Another option is to use a regular expression:

 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, "`$&"); } 

Note: you do not need to hide the backslash: PowerShell does not use them as escape characters. This makes it easy to create regular expressions.

+1
source

Source: https://habr.com/ru/post/957684/


All Articles