如何让Azure Pipeline的PowerShellonTargetMachines任务使用PowerShell Core?
一、修正你的内联脚本错误
你当前脚本里用powershell -Version 7.4.2的问题在于:powershell.exe是Windows PowerShell的执行程序,它无法识别PowerShell Core的版本号,自然会报错。PowerShell Core的执行程序是pwsh.exe,你需要修改脚本调用它:
if ($PSVersionTable.PSVersion -lt [Version]"7.4.2") { Write-Output "切换到PowerShell 7.4.2执行" # 直接调用PowerShell Core的执行文件路径 & "C:\Program Files\PowerShell\7\pwsh.exe" -File $MyInvocation.MyCommand.Definition exit } # 这里写你的PowerShell Core业务逻辑 Write-Output "当前PowerShell版本: $($PSVersionTable.PSVersion)"
说明:PowerShellOnTargetMachines任务默认会启动Windows PowerShell,脚本检测到版本不符合后,会调用pwsh.exe重新运行当前脚本,后续逻辑就会在PowerShell Core环境下执行。
二、直接连接PowerShell Core的WinRM端点
如果你不想依赖脚本切换,也可以直接在任务中通过Invoke-Command连接到PowerShell Core注册的WinRM端点(前提是你已经在目标机器上运行Enable-PSRemoting启用了Core的远程功能):
# 替换为你的目标机器名和凭据逻辑 $cred = Get-Credential Invoke-Command -ComputerName "目标机器名" -ConfigurationName "Microsoft.PowerShell" -ScriptBlock { # 这里的代码会在PowerShell Core环境执行 $PSVersionTable } -Credential $cred
注:可以通过在目标机器的PowerShell Core中运行Get-PSSessionConfiguration,确认Core对应的端点名称(通常为Microsoft.PowerShell或Microsoft.PowerShell.7)。
三、关于为何没有新版PowerShellOnTargetMachines支持Core
微软目前的策略是推进现代任务体系,PowerShellOnTargetMachines属于较旧的任务,官方更推荐使用PowerShell任务(可指定使用PowerShell 7)配合远程连接逻辑,而非更新旧任务。现代PowerShell任务支持直接选择PowerShell版本,你可以在任务配置的"Version"选项中选择"7.x",然后在脚本中自行处理远程到目标机器的逻辑。
内容的提问来源于stack exchange,提问作者mpmarven

