执行脚本时转义&符号

时间:2016-12-02 10:08:33

标签: wpf powershell

我试图通过指向powershell.exe路径从WPF执行PowerShell。我有以下代码

我得到的错误是

  

不允许使用与号(&)字符。 &运营商留作将来使用;用双引号(“&”)包装&符号,将其作为字符串的一部分传递。

string PSPath = string.Concat(Environment.SystemDirectory, "\\WindowsPowerShell\\v1.0\\powershell.exe");
string ScriptPath = string.Concat(PSPath, " -ExecutionPolicy Unrestricted -Command ");
string CommandPath = string.Concat("\"& {&'", regex[0].ToString(), "'", regex[1].ToString(), "}\"");
ScriptPath = string.Concat(ScriptPath, CommandPath);
using (Process p = new Process())
{
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = PSPath;
    p.StartInfo.Arguments = ScriptPath;
    p.Start();
    string error = p.StandardOutput.ReadToEnd();
}

我的脚本如下所示:

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -Command "& {&'C:\TestPS\Testps1' -Arg1 -Arg2}"

当我直接将粘贴复制到PowerShell中时执行正常,但不是从WPF应用程序复制。

1 个答案:

答案 0 :(得分:0)

看到你调用ps1的方式,似乎你只想简单地执行ps1。然后不要使用“& ”。

直接调用脚本,如:

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -Command "C:\TestPS\Test.ps1 -Arg1 -Arg2"
相关问题