Passing parameters to powershell script in C#

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi, i have read a lot of posts regarding this issue but i still cant make it to work
http://stackoverflow.com/questions/527513/execute-powershell-script-from-c-sharp-with-commandline-arguments
http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C
http://social.msdn.microsoft.com/Forums/en-SG/csharpgeneral/thread/faa70c95-6191-4f64-bb5a-5b67b8453237
I have a Windows Form with 2 Textboxes
TB_user
TB_office
I also have a powershell script on c:scriptsscript.ps1 that i need to run with 2 parameters
script.ps1 -user TB_user.Tostring() -office TB_office.ToString()
So getting the textbox content as parameters to call the script on a button click, my code is: private void button1_Click(object sender, EventArgs e)
{
string user = TB_user.ToString();
string office = TB_office.ToString();
var scriptfile = @"c:scriptsscript.ps1";


RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();

RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

Pipeline pipeline = runspace.CreatePipeline();

//Heres how you add a new script with arguments
Command myCommand = new Command(scriptfile);
CommandParameter userParam = new CommandParameter("user", user);
myCommand.Parameters.Add(userParam);
CommandParameter officeParam = new CommandParameter("office", office);
myCommand.Parameters.Add(officeParam);

pipeline.Commands.Add(myCommand);

// Execute PowerShell script
results = pipeline.Invoke();

}
}
}

I got the name results doesnt exist in the current context, and also, nothing runs.. :(
Can anybody help?
Thanks

View the full article
 
Back
Top