Devi

Devi

  • NA
  • 55
  • 16.3k

Escape ampersand while executing the script

Dec 8 2016 5:42 AM
I am trying to execute the PowerShell from WPF by pointing to the powershell.exe path. I have the following code
The error I am getting is The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string.
 
http://blog.heshamamin.com/2009/04/calling-powershell-script-in-path-with.html
 
  1. string PSPath = string.Concat(Environment.SystemDirectory, "\\WindowsPowerShell\\v1.0\\powershell.exe");  
  2. string ScriptPath = string.Concat(PSPath, " -ExecutionPolicy Unrestricted -Command ");  
  3. string CommandPath = string.Concat("\"& {&'", regex[0].ToString(), "'", regex[1].ToString(), "}\"");  
  4. ScriptPath = string.Concat(ScriptPath, CommandPath);  
  5. using (Process p = new Process())  
  6. {  
  7.     p.StartInfo.UseShellExecute = false;  
  8.     p.StartInfo.RedirectStandardOutput = true;  
  9.     p.StartInfo.FileName = PSPath;  
  10.     p.StartInfo.Arguments = ScriptPath;  
  11.     p.Start();  
  12.     string error = p.StandardOutput.ReadToEnd();  
  13. }  
My script looks as follows:
 
  1. C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -Command "& {&'C:\TestPS\Testps1' -Arg1 -Arg2}"  
 which is executing fine when I directly copy paste into PowerShell, but not from the Win froms application.

Answers (8)