I am trying to call Powershell script file with parameters in C# using the System.Management.Automation
like this:
using (var ps = PowerShell.Create())
{
try
{
var script = System.IO.File.ReadAllText("MyPsFile.ps1");
ps.Commands.AddScript(script);
ps.AddScript(script);
ps.AddParameter("MyKey1", value1);
ps.AddParameter("MyKey2", value2);
var results = ps.Invoke();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
The Powershell file looks like this:
function MyFunction {
Param (
[Parameter(Mandatory=$true)][string] $MyKey1,
[Parameter(Mandatory=$true)][string] $MyKey1,
)
Process {
..do some stuff
}
}
MyFunction $args[0] $args[1]
If I run the script file inside Powershell like this:
powershell -file MyPsFile.ps1 "Value1" "Value2"
It works fine. But calling the file from within C# is not working. Any idea why?
So I have updated the code like this
var runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
var runSpaceInvoker = new RunspaceInvoke(runspace);
runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
// create a pipeline and feed it the script text
var pipeline = runspace.CreatePipeline();
var command = new Command(@". .\MyScript.ps1");
command.Parameters.Add("MyParam1", value1);
command.Parameters.Add("MyParam2", value2);
pipeline.Commands.Add(command);
pipeline.Invoke();
runspace.Close();
But I am getting the error Powershell ps1 file “is not recognized as a cmdlet, function, operable program, or script file.”
I found this Powershell ps1 file "is not recognized as a cmdlet, function, operable program, or script file."
But it did not solve the problem. Any idea what else could cause this error?