我无法在C#中正确运行带引号的PowerShell代码

时间:2014-03-30 22:22:00

标签: c# powershell

我似乎无法使用引号正确运行PowerShell代码。我有双引号所以C#会把它看作一个引用,但是逃避它。但随后出现问题,我们将变量写入屏幕并且它有引号,正如您所猜测的那样,但是当我将其放入流程时,引号就会消失。

string var = @"function blink {while ($a -ne 1) {$color = get-random -max 17  -min 1
switch($color) {
""1"" {[console]::BackgroundColor = ""Black""}
""2"" {[console]::BackgroundColor = ""DarkBlue""}
""3"" {[console]::BackgroundColor = ""DarkGreen""}
""4"" {[console]::BackgroundColor = ""DarkCyan""}
""5"" {[console]::BackgroundColor = ""DarkRed""}
""6"" {[console]::BackgroundColor = ""DarkMagenta""}
""7"" {[console]::BackgroundColor = ""DarkYellow""}
""8"" {[console]::BackgroundColor = ""Gray""}
""9"" {[console]::BackgroundColor = ""DarkGray""}
""10"" {[console]::BackgroundColor = ""Blue""}
""11"" {[console]::BackgroundColor = ""Green""}
""12"" {[console]::BackgroundColor = ""Cyan""}
""13"" {[console]::BackgroundColor = ""Red""}
""14"" {[console]::BackgroundColor = ""Magenta""}
""15"" {[console]::BackgroundColor = ""Yellow""}
""16"" {[console]::BackgroundColor = ""White""}}
}}
blink";
Console.WriteLine(var);
Console.ReadLine();
System.Diagnostics.Process.Start("powershell.exe", @"powershell.exe -ExecutionPolicy Bypass -Command {" + var + "}");

1 个答案:

答案 0 :(得分:2)

看起来您可能需要转义引号才能让PowerShell正确解释您的代码。从Microsoft pagethis other page来看,PowerShell转义字符是严重的重音:`

第二个页面上的示例用法是从命令提示符转义,但在这种情况下应该适用相同的原则。

我使用以下方法测试了部分代码:

System.Diagnostics.Process.Start("powershell.exe", @"powershell.exe -noexit -ExecutionPolicy Bypass -Command {[console]::BackgroundColor = '""Magenta'""}");

它产生了一个带有洋红色背景的PowerShell提示符,所以它应该只是用``""替换字符串中""的所有实例。

编辑:有关转义的其他信息:Escaping quotes in powershell.exe via command prompt。此外,DeveloperGuo在评论中链接的答案看起来很有希望。