Question : Running a powershell command from C#

This is related to EE issue:
http://www.experts-exchange.com/Programming/Languages/Scripting/MSH-Monad/Q_23666325.html

I am trying to run a PS command from my C# event handler  and get the following error
"The term 'write-error Error 2>&1 | out-null' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again."

Attached is my C# method that runs a PS command

The invocation is done by:

const string COMMAND = "write-error Error 2>&1 | out-null";
 QPSCmdlet.RunCommand(COMMAND, new Dictionary());

This is done in order to change the $? value to false

Thanks
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
public static string RunCommand(string command, IDictionary dictionary)
        {
            // create Powershell runspace
 
            Runspace runspace = RunspaceFactory.CreateRunspace();
 
            // open it
 
            runspace.Open();
 
            var cmd = new Command(command);
            foreach (var pair in dictionary)
            {
                cmd.Parameters.Add(pair.Key, pair.Value);
            }
            // create a pipeline and feed it the command
 
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.Add(cmd);
 
            Collection results = pipeline.Invoke();
 
            // close the runspace
 
            runspace.Close();
 
            // convert the command result into a single string
 
            var stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
 
            return stringBuilder.ToString();
        }
Open in New Window Select All

Answer : Running a powershell command from C#

I guess what I am going for is where is this EventHandler ran? Does a cmdlet call it or a console application? If it is a console app use return values like you normally would and from Powershell you can access it via $LASTEXITCODE
Random Solutions  
 
programming4us programming4us