calling powershell functions through c#

房东的猫 提交于 2019-12-11 17:35:06

问题


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();


来源:https://stackoverflow.com/questions/48418810/calling-powershell-functions-through-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!