Search This Blog

Sunday, September 4, 2016

Execute PowerShell Script from C#

Option 1

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
startInfo.Arguments = @"& 'c:\Scripts\test.ps1'";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();

string output = process.StandardOutput.ReadToEnd();
Assert.IsTrue(output.Contains("StringToBeVerifiedInAUnitTest"));


string errors = process.StandardError.ReadToEnd();
Assert.IsTrue(string.IsNullOrEmpty(errors));

With the contents of the script being:
$someVariable = "StringToBeVerifiedInAUnitTest"
$someVariable


Option 2

C:\Foo1.PS1 Hello World Hunger C:\Foo2.PS1 Hello World


scriptFile = "C:\Foo1.PS1"


parameters = "parm1 parm2 parm3" ... variable length of params

private static void RunPowershellScript(string scriptFile, string scriptParameters)
{
    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    runspace.Open();
    RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
    Pipeline pipeline = runspace.CreatePipeline();
    Command scriptCommand = new Command(scriptFile);
    Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
    foreach (string scriptParameter in scriptParameters.Split(' '))
    {
        CommandParameter commandParm = new CommandParameter(null, scriptParameter);
        commandParameters.Add(commandParm);
        scriptCommand.Parameters.Add(commandParm);
    }
    pipeline.Commands.Add(scriptCommand);
    Collection<PSObject> psObjects;
    psObjects = pipeline.Invoke();
}

Option 3


string cmdArg = ".\script.ps1 -foo bar"            Collection<PSObject> psresults;
using (Pipeline pipeline = _runspace.CreatePipeline())
            {
                pipeline.Commands.AddScript(cmdArg);
                pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                psresults = pipeline.Invoke();
            }
return psresults;


Option 4


Here is a way to add Paramaters to the script if you used pipeline.Commands.AddScript(Script);

 This is with using an HashMap as paramaters the key being the name of the variable in the script and the value is the value of the variable.

 pipeline.Commands.AddScript(script));


 FillVariables(pipeline, scriptParameter);


 Collection<PSObject> results = pipeline.Invoke();

And the fill variable method is:

private static void FillVariables(Pipeline pipeline, Hashtable scriptParameters)
{
    // Add additional variables to PowerShell
    if (scriptParameters != null)
    {
        foreach (DictionaryEntry entry in scriptParameters)
        {
            CommandParameter Param = new CommandParameter(entry.Key as String, entry.Value);
            pipeline.Commands[0].Parameters.Add(Param);
        }
    }
}

this way you can easily add multiple parameters to a script. Ive also noticed that if you want to get a value from a variable in you script like so:

Object resultcollection = runspace.SessionStateProxy.GetVariable("results");


Others URL:
http://olivier-richard.azurewebsites.net/call-a-powershell-script-from-c-code/
http://www.c-sharpcorner.com/forums/powershell-script-run-from-c-sharp-app
http://en.community.dell.com/techcenter/systems-management/w/wiki/3479.executing-microsoft-powershell-scripts-that-use-the-vmware-powercli-snap-in-via-c-and-microsoft-net
http://jeffmurr.com/blog/?p=142




No comments:

Post a Comment