calling powershell functions through c#

2019-08-26 07:29发布

问题:

I'm trying to call PowerShell function through c# code.

**#This is sample PowerShell function**

function Add-num {

param($int1,$int2)

Write-Host ($int1 + $int2)

}


**#This is my c# code**

 class Program
    {

        static void Main(string[] args)
        {
            String file = @"E:\powershell\Untitled3.ps1";

            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();

            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddScript(file);
                PowerShellInstance.AddCommand("Add-num").AddParameters(new Dictionary<string, string>
                {
                    {"int1","6" },
                    {"int2","7" }
                });






               // Collection<PSObject> PSOutput = PowerShellInstance.Invoke();

                foreach (PSObject outputItem in PowerShellInstance.Invoke())
                {
                    Console.WriteLine(outputItem.BaseObject);
                }
                runspace.Close();
        }
    }
}

Error: An unhandled exception of type 'System.Management.Automation.CommandNotFoundException' occurred in System.Management.Automation.dll

Additional information: The term 'Add-num' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

The above error is thrown when I execute this code. But when I run from PowerShell code works fine. I've checked the file path and file name everything is fine can anyone help me on this. The error is pointing at Invoke.

回答1:

I've done the following before:

string command = @"C:\temp.ps1";
var fileName = "powershell";
var args = $"-ExecutionPolicy unrestricted . '{command}'";

var process = CreateProcess(fileName, args);
process.Start();