2013-05-06 77 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問題。