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