Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell command through C# code

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.

like image 651
user2034092 Avatar asked Feb 07 '26 00:02

user2034092


1 Answers

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.

like image 192
Neolisk Avatar answered Feb 09 '26 15:02

Neolisk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!