通过C#代码执行Powershell命令
我想通过C#代码添加Powershell命令或脚本(正确吗?)变量声明,并将默认值存储在C#变量中.
例如,在Powershell中,我输入以下行
$user = 'Admin'
我想在C#代码中添加此行.
powershell.AddScript(String.Format("$user = \"{0}\"", userName));
要么
powershell.AddCommand(String.Format("$user = \"{0}\"", userName));
我尝试使用AddCommand(),但会引发异常.我使用PS 2.0.
解决方法:
根据这篇文章How to run PowerShell scripts from C#,您将需要以下内容:
// 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<psobject> results = pipeline.Invoke();
// close the runspace
runspace.Close();
另请参见此处关于Stackoverflow的Run Powershell-Script from C# Application问题.