Powershell command through C# code

早过忘川 提交于 2019-12-01 06:04:53

问题


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'

I want to add this line in C# code.

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

or

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

I try with AddCommand() but it throws exception. I use PS 2.0.


回答1:


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();

Also see Run Powershell-Script from C# Application question here on Stackoverflow.



来源:https://stackoverflow.com/questions/16398171/powershell-command-through-c-sharp-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!