I have a script that uses the -Authentication parameter of Invoke-RestMethod and therefore requires PowerShell 7+. I'd like my script to check for PowerShell 7, install it if necessary, and restart itself in PowerShell 7 with it's current parameters to continue executing.
Here's what I have so far:
# 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 }
}
Now, this works, but it feels really dirty.
- Is there a cleaner/safer way to accomplish what I'm wanting?
- Is there a way to get around the lack of the
-Authenticationparameter onInvoke-RestMethodwithout needing PowerShell 7 that I missed?
Thanks in advance!