通过C#调用PowerShell函数 [英] calling powershell functions through c#

查看:217
本文介绍了通过C#调用PowerShell函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过C#代码调用PowerShell函数。

**#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:powershellUntitled3.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();
        }
    }
}

错误:系统管理.Automation.dll中出现‘System.Management.Automation.CommandNotFoundException’类型的未处理异常

附加信息:术语‘Add-Num’未被识别为cmdlet、函数、脚本文件或可操作程序的名称。请检查名称的拼写,或者如果包含路径,请验证该路径是否正确,然后重试。

当我执行此代码时抛出上述错误。但当我从PowerShell运行时,代码运行得很好。我已经检查了文件路径和文件名,一切正常,有人能帮我解决这个问题吗?错误指向Invoke。

推荐答案

我以前做过以下操作:

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

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

这篇关于通过C#调用PowerShell函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆