powershell-coreazure-pipelines-release-task

Force azure pipeline task PowerShellonTargetMachines to use Powershell Core


Is there a way to make the azure pipeline task PowerShellonTargetMachines hit the powershell core endpoint instead of the windows powershell endpoint?

Changing the machine profile doesn't seem to be an option for us and I tried running Enable-PSRemoting on powershell 7 on a target machine and then trying to run an inline script targetting that machine via the PowerShellonTargetMachines task that include this code to start a powershell 7.4.2 instance but it still says 7.4.2 doesn't exist even though it is installed and clearly from the error message it's still hitting windows powershell instead of powershell core. Why isn't there a newer version of PowerShellonTargetMachines that directly supports powershell core.

if ($PSVersionTable.PSVersion -lt [Version]"7.4.2") {
  Write-Output "Restarting powershell to get correct version"
  powershell -Version 7.4.2 -File $MyInvocation.MyCommand.Definition
  exit
}
2024-11-06T04:51:07.7257943Z 
2024-11-06T04:51:07.7693744Z Cannot start Windows Powershell version 7.4.2 because it is not installed```


Solution

  • I am afraid that there is no built-in option in PowerShellOnTargetMachines Task can force the task to use PowerShell core.

    Is there a way to make the azure pipeline task PowerShellonTargetMachines hit the powershell core endpoint instead of the windows powershell endpoint?

    Since you have installed PowerShell core 7.4.2 on your machine, you can use the pwsh command to run the script. In this case, it will directly use the PowerShell core instead of windows powershell.

    For example:

    pwsh
    pwsh -File $MyInvocation.MyCommand.Definition
    

    Pipeline task sample:

    - task: PowerShellOnTargetMachines@3
      inputs:
        Machines: 'xx'
        UserName: 'xx'
        UserPassword: 'xx'
        InlineScript: |
          Write-Output "Restarting powershell to get correct version"
          pwsh
          pwsh -File $MyInvocation.MyCommand.Definition
    

    If you see the error below:

    pwsh : The term 'pwsh' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

    This means that you haven't set the Windows Environment variable for the PowerShell core. In this case, you can find the pwsh.exe file path(e.g. C:\Program Files\PowerShell\7\pwsh.exe) and run the pwsh.exe.

    For example:

    &"C:\Program Files\PowerShell\7\pwsh.exe"
    &"C:\Program Files\PowerShell\7\pwsh.exe" -File $MyInvocation.MyCommand.Definition