Sam Stephenson
Sam Stephenson

Reputation: 5190

Assign variables to powershell using C#

I'am tring to call a powershell script and pass through a parameter. I would all so like to pass through a more than one parameter eventually

        RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();
        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

        Pipeline pipeline = runspace.CreatePipeline();

        String scriptfile = "..\\..\\Resources\\new group.ps1";

        Command myCommand = new Command(scriptfile, false);

        CommandParameter testParam = new CommandParameter("test3");

        myCommand.Parameters.Add(testParam);


        pipeline.Commands.Add(myCommand);
        Collection<PSObject> psObjects;
        psObjects = pipeline.Invoke();
        runspace.Close();

The problem seems to be ... well nothing happens. Is this how to correctly assign the varibles? Giving test powershell script

# creates group
net localgroup $username /Add
# makes folder
#mkdir $path

Upvotes: 2

Views: 1798

Answers (2)

Keith Hill
Keith Hill

Reputation: 202032

This line of code:

CommandParameter testParam = new CommandParameter("test3");

Creates a parameter named test3 that has a value of null. I suspect you want to create a named parameter e.g.:

CommandParameter testParam = new CommandParameter("username", "test3");

And you're script needs to be configured to accept parameters e.g.:

--- Contents of 'new group.ps1 ---
param([string]$Username)
...

Upvotes: 4

Chris N
Chris N

Reputation: 7499

The PowerShell script needs to be setup to accept parameters:

Try adding the following to the top of that script and re-testing:

param([string]$username)

Alternatively, you could add the folowing line to the top of your script:

$username = $args[0]

Good luck.

Upvotes: 1

Related Questions