3

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
  • 1
    Shouldn't you use AddScript method instead? Commented May 6, 2013 at 13:15

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.