Home > Back-end >  Not getting expected output when calling PowerShell function from Azure PowerShell Task
Not getting expected output when calling PowerShell function from Azure PowerShell Task

Time:05-20

Given:

  • PowerShell 5.1
  • Azure DevOps Server 2019

I'm trying to call my function directly from my Azure PowerShell Task Arguments, is this possible? I'm not getting any expected output.

param([String] $Name, [Int] $Age, [String] $Path)

Function Foo
{
    Param(
        [String]
        $Name
    ,
        [Int]
        $Age
    ,
        [string]
        $Path
    )
    Process
    {
        write-host "Hello World"
        If ("Tom","Dick","Jane" -NotContains $Name)
        {
            Throw "$($Name) is not a valid name! Please use Tom, Dick, Jane"
        }
        If ($age -lt 21 -OR $age -gt 65)
        {
            Throw "$($age) is not a between 21-65"
        }
        IF (-NOT (Test-Path $Path -PathType ‘Container’))
        {
            Throw "$($Path) is not a valid folder"
        }
        # All parameters are valid so New-stuff"
        write-host "New-Foo"
    }
}

enter image description here

CodePudding user response:

If you execute your script directly, it will simply define the Foo function, but never call it.

Place the following after the function definition in your script in order to invoke it with the arguments that the script itself received, using the automatic $args variable via splatting:

Foo @args

The alternative would be not to invoke a script file, but a piece of PowerShell code (in PowerShell CLI terms, this means using the
-Command parameter rather than -File), which would allow you to use ., the dot-sourcing operator to first load the function definition into the caller's scope, which then allows it to be called:

. "$(System.DefaultWorkingDirectory)/_RodneyConsole1Repo/FunctionExample.ps1"
Foo -Name Rodney -Age 21 -Path ""
  • Related