2016-12-02 87 views
0

我试图通过指向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应用程序。

+0

出了什么问题'-Command “C:\将TestPS \ Test.ps1 -Arg1 -Arg2”'? –

+0

任何更新,请尝试几种方式,但没有运气 – Dotnet

回答

0

看到你正在调用ps1的方式,看起来你只想简单地执行ps1。然后请勿使用“&”。

调用脚本直接,如:

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