I created a powershell script that consists of:
param($ServerName, $Location)
"Application Name: $ServerName"
"Location: $Location"
when I am in the powershell and I run .\Params.ps1 ConsoleApp1 Washington, D.C. it will display:
Application Name: ConsoleApp1
Location: Washington D.C.
So I know this works just fine. Now I am wanting to take this to c# and perform parameter passing.
In my console application, I created the following:
static void Main(string[] args)
{
string[] scriptParam = { "ConsoleApp1", "Washington, D.C."};
string powerShell = PerformScript(scriptParam);
Console.WriteLine(powerShell);
Console.WriteLine("\nPowershell script excuted!!");
Console.ReadLine();
}
static string PerformScript(string scriptParameters)
{
InitialSessionState runspaceConfiguration = InitialSessionState.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddCommand(@"C:\Users\users\source\repos\ConsoleApp1\powershell\Params.ps1");
foreach (string scriptParameter in scriptParameters)
{
ps.AddParameter(scriptParameter);
}
Collection<PSObject> psObjects = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new();
foreach (PSObject item in psObjects)
{
stringBuilder.AppendLine(item.ToString());
}
return stringBuilder.ToString();
}
but when I run the program I get an Exception Unhandled on the line
Collection<PSObject> psObjects = pipeline.Invoke();
System.Management.Automation.PSInvalidOperationException: 'The pipeline does not contain a command.'
Am I doing something incorrect when passing the parameters?
Updated code:
static string PerformScript(string[] scriptParameters)
{
InitialSessionState runspaceConfiguration = InitialSessionState.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
using (var ps = PowerShell.Create())
{
var result = ps.AddCommand(@"C:\Users\users\source\repos\ConsoleApp1\powershell\Params.ps1")
.AddArgument("ConsoleApp1")
.AddArgument("Washington, D.C.")
.Invoke();
foreach (var o in result)
{
Console.WriteLine(o);
}
}
Collection<PSObject> psObjects = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new();
foreach (PSObject item in psObjects)
{
stringBuilder.AppendLine(item.ToString());
}
return stringBuilder.ToString();
}