I am having trouble with escaping characters in C# to run Powershell scripts. In order to make the issue short. I did the following test.
I can run the following command successfully in Powershell ISE.
New-Issue -Summary "Test Summary" -Description "test `"test`" "
Basically, the script insert a record into a database table. The table has two columns: summary and description. The value for summary is "Test Summary" and the value for description is " test "test" ".
I was trying to run the same Powershell command in C# by doing the following thing.
try{
command = "New-Issue -Summary \"Test Summary \" -Description \"test `\"test`\" \"";
powerShellInstance = PowerShell.Create();
powerShellInstance.AddScript(command);
Collection<PSObject> PSOutput = powerShellInstance.Invoke();
...
}
catch(Exception e)
{
return e.Message;
}
I got error in C#. The error cannot be caught by the try catch statement. But I can see the exceptions kept thrown in output in VisualStudio, the code will hang there forever:
Exception thrown: 'System.Management.Automation.ParameterBindingException' in System.Management.Automation.dll Exception thrown: 'System.Management.Automation.ValidationMetadataException' in Microsoft.PowerShell.Commands.Utility.dll Exception thrown: 'System.Management.Automation.ParameterBindingValidationException' in System.Management.Automation.dll
If the description does not contain double quotes. Such as
command = "New-Issue -Summary \"Test Summary \" -Description \"test \"";
The script runs fine in C#. I believe I am escaping the double quotes correctly here. Does anyone know what is going wrong here?
Please be noted this example is just for demonstrating purpose. I know I can insert data into table in C# in an easy way. I just want to figure out how should I run Powershell scripts in C# correctly.
Thank you.
P.S: I forgot to mention that I prefer using ` to escape the double quotes to using single quote in the description fields. Because the value for description is getting from a textbox. By doing so, i can only handle double quotes from the textbox and leave everything as it is.