Pass PowerShell arguments to Process.Start

Viewed 1977

I am trying to convert some of my bat scripts over to C#. I have the entire program ported except for the PowerShell execution line.

To keep things simple, I was trying to just call the PowerShell command from cmd. I am able to do so but its not taking the complex arguments and parameters that go along with the PowerShell command.

Here is the command if I run directly from cmd or bat file.

powershell -Command "& {asnp 'citrix*'; remove-BrokerTag -Name 'Somename' -Machine 'domain\server' -AdminAddress 'SomeServer';}"

I was using this code to invoke cmd and run my powershell command.

string strCmdText;
strCmdText = "'/C powershell " + "-Command " + "&" + " { asnp 'citrix*'; add - BrokerTag - Name 'Somename' - Machine 'domain\server'" + (listboxvariable) + " - AdminAddress 'ServerXX'; }'" + " & pause";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);

I get this error "Cannot process the command because of a missing parameter. A command must follow -Command."

As you can see there are a lot of arguments in this PowerShell command.

Is there an easier way to do this? or I am just missing something simple?

1 Answers

In your original PowerShell line, the Command is surrounded by double quotes.

Try this:

strCmdText = "/C powershell " + "-Command " + "\"& " + "{ asnp 'citrix*'; add - BrokerTag - Name 'Somename' - Machine 'domain\server'" + (listboxvariable) + " - AdminAddress 'ServerXX'; }\"" + " & pause";

Notice the use of \" escape sequences to add the missing double quotes that are present in your original command line.

Related