Execute .ps1 file as parameter from a C# project

Viewed 134

I am trying to execute a .ps1 file from my C# console application. Using the code provided below you can see what I am trying to do:

public static void execitePs(string originalString)
{
        using (PowerShell ps = PowerShell.Create())
        {
            // specify the script code to run.
            ps.AddScript(@"C:\PnP\test_script_json.ps1");

            // specify the parameters to pass into the script.
            ps.AddParameter("originalString", originalString);

            // execute the script and await the result.
            var pipelineObjects = ps.Invoke();
            // print the resulting pipeline objects to the console.


            foreach (dynamic item in pipelineObjects)
            {
                Console.WriteLine(item);

            }
        }
}

Basically I am trying to supply the file path to the AddScript method as explained in the Microsoft example. This should call the script file and execute it. Here is the script file content:

param ($originalString)

$JSONString = @"
    $originalString
"@


Write-Output HEREEEEEEEE
$cusomObject = ConvertFrom-Json $JSONString

Write-Host $cusomObject.Name

The whole process is basically taking some JSON as parameter and printing the property name.

Even if the JSON is missing the property it should print the HEREEEEEEEE string to the console.

As a result I am not getting any output since the pipelineObjects Collection is empty after invoking the script.

Moreover, I have managed to execute it successfully using the following method:

Process.Start(@"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe", @"-File ""C:\PnP\test_script_json.ps1"" """ + originalString + "");

but using this is not so flexible.

Any ideas how I can do the same using the PowerShell object?

Any help/idea is appreciated!

Best regards, Dimitar

2 Answers

I use this helper method.

private Process CreateAndStartProcess(string fileName, string arguments)
{
    var startInfo = new ProcessStartInfo
    {
        WindowStyle = ProcessWindowStyle.Normal,
        FileName = fileName,
        WorkingDirectory = @"C:\Windows\SysWOW64\WindowsPowerShell\v1.0",
        Arguments = arguments,
        RedirectStandardOutput = true,
        CreateNoWindow = false,
        RedirectStandardError = true,
        UseShellExecute = true
    };

    var process = new Process
    {
        StartInfo = startInfo
    };

    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    return process;
}

You can launch it via

var arguments = @"-File C:\PnP\test_script_json.ps1" + originalString;
var process = CreateAndStartProcess("powershell.exe", arguments);

This is because the commands are returning a new Powershell-Instances so your changes are not actually applied

You need to either do:

ps
    .AddScript(@"C:\PnP\test_script_json.ps1")
    .AddParameter("originalString", originalString)
    .Invoke();

or

        // specify the script code to run.
        ps = ps.AddScript(@"C:\PnP\test_script_json.ps1");

        // specify the parameters to pass into the script.
        ps = ps.AddParameter("originalString", originalString);

        // execute the script and await the result.
        var pipelineObjects = ps.Invoke();
        // print the resulting pipeline objects to the console.
Related