Azure CLI through Azure Devops Build Pipeline

Azure CLI through Azure Devops Build Pipeline

powershell.exe: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index.

·

2 min read

While trying to run a Powershell script that has a dependency on the Azure CLI, I was getting the following error:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a\_temp\azureclitaskscript1621307438872.ps1'"
...

D:\a\1\s\src\Infrastructure\MyPsScript.ps1 : Index was out of range. Must be non-negative and 
less than the size of the collection.
Parameter name: index
At D:\a\_temp\azureclitaskscript1621307438872.ps1:3 char:1

This is the following Stage:

- stage: AzureResourcesUpdates
  displayName: Manage some Azure resources

  jobs:
  - job: AzureInfra
    displayName: Create Azure Resources
    pool:
      vmImage: 'windows-latest'
    steps:
    - task: AzureCLI@2
      inputs:
        azureSubscription: 'Some Service Connection'
        scriptType: 'ps'
        scriptLocation: 'scriptPath'
        scriptPath: '$(Build.SourcesDirectory)\src\Infrastructure\MyPsScript.ps1'
        arguments: '$(Environment) $(Var1) $(Var2) 
        powerShellErrorActionPreference: 'continue'
        addSpnToEnvironment: true
        useGlobalConfig: true
        workingDirectory: '$(Build.SourcesDirectory)\src\Infrastructure'

From the logs, the specified script or inline script is wrapped in by another Powershell script located in the D:\a_temp directory. You can see the contents of the wrapper by adding the following Powershell task:

    - task: PowerShell@2
      inputs:
        targetType: 'inline'
        script: 'Get-ChildItem D:\a\_temp -Filter *.ps1 -File | % {Get-Content "D:\a\_temp\$($_.Name)"}'

If you try to access $_ directly, it will refer to a location similar to D:\a\1\ which is why D:\a_temp is explicitly declared as part of the filepath.

After playing around with authenticating through the AzureCLI task and running a separate Powershell task, I reverted back to essentially what was above with one difference. The scriptType was change to pscore. After this change, the run was able to progress past this error.

scriptType: 'pscore'

I would have prefered to run this step as part of a Release pipeline, but would require some work in allowing access to the script, which is currently lives in a git repository. I currently lack access to add in Tasks from the Marketplace that would allow git repository cloning.

References