2016-12-02 45 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"