2013-05-06 72 views
3

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

$user = 'Admin' 

我想补充的C#代码这一行。

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

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

我尝试用AddCommand(),但它抛出异常。我使用PS 2.0。

+1

不应该使用'AddScript'方法吗? – BartekB 2013-05-06 13:15:12

回答

4

根据这篇文章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(); 

在此还看到#2 Run Powershell-Script from C# Application问题。