【问题标题】:How to call a function from one script in another script?如何从另一个脚本中的一个脚本调用函数?
【发布时间】:2019-10-07 14:50:21
【问题描述】:

我正在编写一个集成测试,并试图从我的测试中工作的 prod 脚本中获取一个函数调用。现在,每当我尝试调用特定函数时,它只会运行整个脚本。

在 Integration.ps1 我有

. .\AddStart.ps1
Start -job $job

在 AddStart.ps1 我有

function main()
{

Write-Host "This is Main"
Start($job)
}
function Start($job)
{

Write-Host "This is start $job"
}
Main

每当我在 Powershell 中运行集成时,它都会输出 这也是主要的。

我只想将 $job 变量传递给 Start 而不进入 main。

【问题讨论】:

    标签: powershell integration-testing


    【解决方案1】:

    您的自定义模块是在 $env:ModulePath 目录中还是在脚本目录的子目录中

    主脚本

    Import-Module -Name .\ModuleTest
    Test
    

    Module Script 位于名为 ModuleTest 的目录和名为 ModuleTest.psm1 的文件中

    Function Test { Write-Information -MessageData "My Test" -InformationAction Continue }
    

    另外,您正在做的是点源您的原始脚本。 Start 是 Start-Job 的别名。别名在函数之前首先执行,所以这是一个问题。看一下这个: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6

    【讨论】:

      【解决方案2】:

      您的代码在文件的最后一行显式执行Main 函数。您可以在 AddStart.ps1 中执行类似的操作...

      Param([switch] $DontExecuteMainFunction);
      
      function main()
      {
          Write-Host "This is Main"
          Start($job)
      }
      
      function Start($job)
      {
      
          Write-Host "This is start $job"
      }
      
      if(-not $DontExecuteMainFunction){
          Main
      }
      

      然后在 Integration.ps1 点源文件如下:

      . .\AddStart.ps1 -DontExecuteMainFunction
      Start($job)
      

      如果您排除 -DontExecuteMainFunction(例如您现有的代码),它将恢复为当前行为。

      【讨论】:

        【解决方案3】:

        这是因为模块末尾的 Main 函数。我删除了它并从 PowerShell 中调用了该函数,它起作用了。感谢您的回答。

        【讨论】:

          【解决方案4】:

          您是否尝试过将 .ps1 保存为 .psm1,然后导入该模块,然后运行自定义函数?

          【讨论】:

          • 我刚刚尝试过,当将 .psm1 保存到我的当前目录然后尝试从集成中调用它时,它说在执行 Import-Module AddStart 时找不到模块
          • 将它添加到模块不会有帮助。 Main 函数将在加载模块时调用,就像在点源文件时一样。
          猜你喜欢
          • 1970-01-01
          • 2017-11-09
          • 1970-01-01
          • 1970-01-01
          • 2011-06-01
          • 2022-08-02
          • 1970-01-01
          • 2012-01-11
          • 2012-07-13
          相关资源
          最近更新 更多