使用C#生成PowerShell脚本时,转义字符 [英] Escape characters when generating Powershell scripts using C#

查看:229
本文介绍了使用C#生成PowerShell脚本时,转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



然后,它是Powershell必需的转义字符。

有关转义字符的良好方法的任何建议吗?

  public static partial class StringExtensions 
{
/ *
PowerShell特殊转义序列

转义序列特殊字符
`n新行
`r回车
`t Tab
`a Alert
`b Backspace
`双引号
`'单引号
``后引号
`0 Null
* /

public static string FormatStringValueForPS(this string value)
{
if(value == null)return value;
return value.Replace(\,`\)。替换(',`');
}
}

用法:

  var valueForPs1 = FormatStringValueForPS(My text with \double quotes \。More Text); 
var psString =$ value = \+ valueForPs1 +\;;


解决方案

另一种选择是使用regex: / p>

  private static Regex CharactersToEscape = new Regex(@[']); //扩展字符集为requird 


public string EscapeForPowerShell(string input){
// $&是匹配的字符
return CharactersToEscape.Replace(input,`$&);
}

注意:您不需要转义反斜杠:PowerShell不使用它们作为转义字符。这使得编写正则表达式更容易一些。


I use VS2010, C#, .NET 3.5 for generate Powershell scripts (ps1 files).

Then, it is required escape characters for Powershell.

Any suggestions about it for develop good method that escape 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("'", "`'");
        }
    }

Usage:

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

解决方案

The other option would be to use a regex:

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 don't need to escape backslashes: PowerShell does not use them as escape characters. This makes writing regexes somewhat easier.

这篇关于使用C#生成PowerShell脚本时,转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆