Search code examples
c#powershellvariable-assignmentpipeline

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

Solution

  • 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)
    ...