Powershell命令通过C#代码

我想通过C#代码添加Powershell命令或脚本(什么是正确的?)变量声明,默认值存储在C#变量中。 例如,在Powershell中我输入以下行

$user = 'Admin' 

我想在C#代码中添加这一行。

 powershell.AddScript(String.Format("$user = \"{0}\"", userName)); 

要么

 powershell.AddCommand(String.Format("$user = \"{0}\"", userName)); 

我尝试使用AddCommand()但它抛出exception。 我用的是PS 2.0。

根据这篇文章如何从C#运行PowerShell脚本 ,你需要这样的东西:

 // create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace(); // open it runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(String.Format("$user = \"{0}\"", userName)); pipeline.Commands.AddScript("#your main script"); // execute the script Collection results = pipeline.Invoke(); // close the runspace runspace.Close(); 

另请参阅Stackoverflow上的C#Application问题中的Run Powershell-Script 。