1

我有一个使用Invoke-RestMethod-Authentication参数的脚本,因此需要 PowerShell 7+。我希望我的脚本检查 PowerShell 7,在必要时安装它,然后使用当前参数在 PowerShell 7 中重新启动以继续执行。

这是我到目前为止所拥有的:

# Check for required PowerShell version (7+)
if (!($PSVersionTable.PSVersion.Major -ge 7)) {
  try {
    
    # Install PowerShell 7
    if(!(Test-Path "$env:SystemDrive\Program Files\PowerShell\7")) {
      Write-Output 'Installing PowerShell version 7...'
      Invoke-Expression "& { $(Invoke-RestMethod https://aka.ms/install-powershell.ps1) } -UseMSI -Quiet"
    }

    # Refresh PATH
    $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
    
    # Restart script in PowerShell 7
    pwsh "`"$PSCommandPath`"" (($MyInvocation.Line -split '\.ps1[\s\''\"]\s*', 2)[-1]).Split(' ')

  } catch {
    Write-Output 'PowerShell 7 was not installed. Update PowerShell and try again.'
    throw $Error
  } finally { Exit }
}

现在,这行得通,但感觉真的很脏。

  • 有没有更清洁/更安全的方式来完成我想要的?
  • 有没有办法在不需要我错过的 PowerShell 7的情况下解决缺少-Authentication参数的问题?Invoke-RestMethod

提前致谢!

4

0 回答 0