通过C#code PowerShell命令 [英] Powershell command through C# code
问题描述
我想通过C#code PowerShell命令或脚本添加(什么是正确的?)变量声明与存储在C#中的变量默认值。 例如,在PowerShell中我打字以下行
I want to add through C# code Powershell command or script (what is correct?) variable declaration with default value stored in C# variable. For example, in Powershell I typing following line
$user = 'Admin'
我想加入这一行的C#code。
I want to add this line in C# code.
powershell.AddScript(String.Format("$user = \"{0}\"", userName));
或
powershell.AddCommand(String.Format("$user = \"{0}\"", userName));
我尝试用AddCommand(),但它会抛出异常。我用PS 2.0。
I try with AddCommand() but it throws exception. I use PS 2.0.
推荐答案
根据这篇文章的如何从C#运行PowerShell脚本,你需要的东西是这样的:
According to this article How to run PowerShell scripts from C#, you will need something like this:
// 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();
另请参见<一href="http://stackoverflow.com/questions/11120452/run-powershell-script-from-c-sharp-application">Run PowerShell的脚本从#1 C#应用程序的问题在这里。
这篇关于通过C#code PowerShell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!