function - Azure 管道 YAML 文件中的内联 powershell 脚本中是否可以包含函数?

标签 function powershell azure-pipelines-yaml hoisting

我希望能够使用函数简化 AzureCLI 任务中的一些内联 powerscript,类似于以下内容:

  - task: AzureCLI@2
    displayName: "My Task"
    inputs:
      scriptType: pscore
      scriptLocation: inlineScript
      inlineScript: |
        Do-Something "hello" "world"
        Do-Something "goodbye" "world"

        function Do-Something { 
          Param
          (
            [Parameter(Mandatory=$true, Position=0)]
            [string] $Hello,
            [Parameter(Mandatory=$true, Position=1)]
            [string] $World
          )

          Write-Host "$Hello $World"
        }

但是失败并出现以下错误:

+ Do-Something "hello" "world"
+ ~~~~~~~
+ CategoryInfo          : ObjectNotFound: (Do-Something:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : CommandNotFoundException
##[error]Script failed with exit code: 1

这可能吗?如果是这样,我做错了什么?

最佳答案

Mathias R. Jessen提供了关键指针:

使用 Azure 是您的问题的偶然,它源于基本的 PowerShell 行为:

  • 与其他语言不同,PowerShell 执行函数提升,...

  • ...这意味着您必须先声明您的函数然后才能调用它们,即在源代码中您必须将函数定义< em>在任何调用它的语句之前。

相关概念帮助主题,about_Functions不幸的是,历史上并没有明确这一点,但此后已得到纠正。现有 PowerShell 安装的离线帮助需要手动更新才能看到更改。


要为您的代码阐明解决方案:

 - task: AzureCLI@2
    displayName: "My Task"
    inputs:
      scriptType: pscore
      scriptLocation: inlineScript
      inlineScript: |
        # First, declare the function.
        function Do-Something { 
          Param
          (
            [Parameter(Mandatory=$true, Position=0)]
            [string] $Hello,
            [Parameter(Mandatory=$true, Position=1)]
            [string] $World
          )

          Write-Host "$Hello $World"
        }

        # Now you can call it.
        Do-Something "hello" "world"
        Do-Something "goodbye" "world"

关于function - Azure 管道 YAML 文件中的内联 powershell 脚本中是否可以包含函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70018761/

相关文章:

powershell - PowerShell从CSV打印站点母版页

powershell - 按名称前缀对文件进行分组,然后使用 PowerShell 归档 (zip) 每个组

Azure管道: file-trigger for files on root level

c - 得到疯狂的大数字,可能是由于对 double 和整数的不当操作(C 语言)

c - 如何将函数输出(数组)分配给c中的另一个函数?

javascript - 在 jQuery(mousedown) 中调用 JS 函数

PowerShell 如何从日期列表中过滤出日期范围。

azure - 部署的隔离功能应用程序返回 404

python-3.x - Azure YAML 管道 : deploy to Function App without overwriting existing function

python - 从具有数据帧格式的函数返回两个数据帧