2

I want to be able to simplify some inline powerscript in an AzureCLI task using a function, similar to the following:

  - 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"
        }

However this fails with the following error:

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

Is this possible? If so, what am I doing wrong?

1
  • 2
    You need to define the function (iow. execute the statement that starts with the function keyword) before you can call it. Move the Do-Something ... statements below the function definition and it'll work Commented Nov 18, 2021 at 12:09

1 Answer 1

2

Mathias R. Jessen provided the crucial pointer:

The use of Azure is incidental to your problem, which stems from a fundamental PowerShell behavior:

  • Unlike other languages, PowerShell performs no function hoisting, ...

  • ... which means that you must declare your functions before you can call them, i.e., in your source code you must place the function definition before any statements that call it.

The relevant conceptual help topic, about_Functions, historically didn't make that clear, unfortunately, but this has since been corrected. Offline help of existing PowerShell installations would need to be updated manually to see the change.


To spell the solution out for your code:

 - 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"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.