【问题标题】:Can you have a function in an inline powershell script in a Azure pipeline YAML file?您可以在 Azure 管道 YAML 文件的内联 powershell 脚本中使用函数吗?
【发布时间】:2021-12-29 06:41:29
【问题描述】:

我希望能够使用函数在 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

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

【问题讨论】:

  • 您需要先定义函数(iow.执行以function关键字开头的语句),然后才能调用它。将 Do-Something ... 语句移到函数定义下方,它会起作用

标签: function powershell azure-pipelines-yaml hoisting


【解决方案1】:

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

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

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

  • ...这意味着您必须先声明您的函数才能调用它们,也就是说,您必须在源代码中放置函数定义在任何调用它的语句之前

不幸的是,相关的概念性帮助主题 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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-20
    • 2021-11-26
    • 2020-06-21
    • 2022-01-15
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多