If your code cannot find the System.Management.Automation.Runspaces
namespace you need to add a dependency to System.Management.Automation.dll
.
This DLL gets shipped with PowerShell and is by default located in the directory: C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0
To add a reference open your project and right-click "references > add reference" and select the "Browse" button to go to the above mentioned location and select the needed .dll file. Click "add" and the reference will show up in the browse tab with a checked checkbox next to it.
After adding the referenceSystem.Management.Automation.Runspaces
You can run the in other mentioned code to add parameters and execute the PowerShell script. I find it very convenient to use a tuple to store the "key", "value" pairs.
/// <summary>
/// Run a powershell script with a list of arguments
/// </summary>
/// <param name="commandFile">The .ps1 script to execute</param>
/// <param name="arguments">The arguments you want to pass to the script as parameters</param>
private void ExecutePowerShellCommand(string commandFile, List<Tuple<string, string>> arguments)
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
//commandFile is the PowerShell script you want to execute, e.g. "FooBar.ps1"
Command cmd = new Command(commandFile);
// Loop through all the tuples containing the "key", "value" pairs and add them as a command parameter
foreach (var parameter in arguments)
cmd.Parameters.Add(new CommandParameter(parameter.Item1, parameter.Item2));
pipeline.Commands.Add(cmd);
// Execute the PowerShell script
var result = pipeline.Invoke();
}
and the calling code:
string commandFile = @"C:\data\test.ps1";
List<Tuple<string, string>> arguments = new List<Tuple<string, string>>();
arguments.Add(new Tuple<string, string>("filePath", @"C:\path\to\some\file"));
arguments.Add(new Tuple<string, string>("fileName", "FooBar.txt"));
ExecutePowerShellCommand(commandFile, arguments);
Command myCommand = new Command(scriptfile);
and thenpipeline.Commands.Add(myCommand);
solve the escaping issue. – Dunne