【问题标题】:C# Powershell executing custom function from script fileC# Powershell 从脚本文件执行自定义函数
【发布时间】:2021-10-05 06:18:12
【问题描述】:

我有一个包含多个函数的 powershell 脚本文件。我想使用 C# 调用其中一个函数。当我调用我的命令时,它会抛出一个错误

    "The term 'LogIn-System' 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."

这里是一些示例代码:

using (PowerShell powerShellInstance = PowerShell.Create())
{
   powerShellInstance.Runspace = runSpace;

   powerShellInstance
     .AddScript("myfunctions.ps1")
     .Invoke();
   powerShellInstance
     .AddCommand("LogIn-System")
     .AddParameter("SystemName", "Connect");
   Collection<PSObject> PSOutput = await Task.Run(() => 
     powerShellInstance.Invoke());
}

【问题讨论】:

  • AddScript() 应该是命令而不是路径。尝试使用.AddScript(".\myfunctions.ps1") 进行点源,或者使用Import-Module,如.AddScript("Import-Module myfunctions.ps1")。或查看此问题中的其他建议之一:stackoverflow.com/questions/6266108

标签: c# powershell


【解决方案1】:

您必须使用两个单独的调用。一是导入模块,二是你的脚本。由于 Import-Module 是来自先前加载的模块的命令,因此请使用 AddCommand 调用它。使用 AddParameter 函数指定要导入的模块名称。例如:

PS
   .AddCommand("Import-Module")
   .AddParameter("Name", "ExchangeOnlineManagement")
   .Invoke();

PS
   .AddScript([your script name])
   .Invoke();

【讨论】:

    猜你喜欢
    • 2012-12-20
    • 2023-03-10
    • 2017-12-22
    • 2018-11-09
    • 2014-04-06
    • 2010-09-11
    • 1970-01-01
    • 2014-09-12
    • 2014-09-30
    相关资源
    最近更新 更多