DEV Community

iainrough
iainrough

Posted on

Change PowerShell Version used in PowerShell@2 - Azure DevOps Tricks #1

Ran into a pipeline issue when using ConvertFrom-Json -Depth 20 to load a JSON file in a PowerShell@2 task in a DevOps pipeline. The -Depth parameter was throwing an error:

ConvertFrom-Json : A parameter cannot be found that matches parameter name 'Depth'
Error message

What the ConvertFrom-Json docs say?

  • PowerShell 5.1
    • Doesn't list a parameter -Depth.
  • PowerShell 7 (LTS)
    • -Depth: Gets or sets the maximum depth the JSON input is allowed to have. By default, it is 1024. This parameter was introduced in PowerShell 6.2.

What version of PowerShell is PowerShell@2 using?

note: this may differ depending on the Agent that is running the task.

I added a line to the script to get the version:

   Write-Host "Version: ($PSVersionTable.PSVersion)"
Extra line to show PowerShell version

Output:

   Version: 5.1.17763.1852
PowerShell Version running on the Agent

How do we change the version?

This little snippet allows a script defined in a PowerShell@2 task to relaunch in a specific version of PowerShell.

    if ($PSVersionTable.PSVersion -lt [Version]"7.0") {
        Write-Host "Version: $($PSVersionTable.PSVersion)"
        Write-Host "Re-launching as pwsh"
        pwsh -File $MyInvocation.MyCommand.Definition
        exit
    }
From StackOverflow.

Some other options if you want a specific version.

    powershell -Version 2 -File $MyInvocation.MyCommand.Definition
Specify a specific version of powershell

Top comments (1)

Collapse
 
sarafian profile image
Alex Sarafian

I run into this problem two years ago when I run scripts that needed the ConvertFrom-Json through PowerShell remoting on different and older version of Windows.

I discovered that the older the version, the more stability problems there were often without any warning and error.

I ended up solving this by spliting the big array into smaller ones and then running the command and saving them to disk. Then move the files and stich them in an environment that is more capable.