Powershell command through C # code

I want to add C # code or script (what's right?) Through a Powershell command, declaring a variable with the default value stored in a C # variable. For example, in Powershell, I print the following line

$user = 'Admin' 

I want to add this line to C # code.

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

or

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

I am trying to use AddCommand (), but this throws an exception. I am using PS 2.0.

+3
source share
1 answer

According to this article, How to run PowerShell scripts with 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 a C # Application here in Stackoverflow.

+4
source

Source: https://habr.com/ru/post/1489652/


All Articles