Skip to content

Instantly share code, notes, and snippets.

@AfroThundr3007730
Last active December 9, 2024 07:08
Show Gist options
  • Save AfroThundr3007730/d51311cdd9b5adaa8e53256768e8fe53 to your computer and use it in GitHub Desktop.
Save AfroThundr3007730/d51311cdd9b5adaa8e53256768e8fe53 to your computer and use it in GitHub Desktop.
Guard functions for powershell version and elevation level
# Only run if elevated as administrator
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$admin = [Security.Principal.WindowsBuiltInRole]::Administrator
if (!([Security.Principal.WindowsPrincipal]$identity).IsInRole($admin)) {
Write-Output 'We are not elevated, launching elevated powershell...'
Start-Process -FilePath powershell.exe -Verb RunAs -ArgumentList $MyInvocation.MyCommand.Source
Start-Sleep 10
exit 0
}
# Only run in PowerShell 7 or higher
if ($PSVersionTable.PSVersion.Major -lt 7) {
Write-Output 'This script requires PowerShell 7 or later.'
#TODO: Add logic for PS6 on Linux
$pwsh = 'C:\Program Files\PowerShell\7\pwsh.exe'
if (([IO.FileInfo]$pwsh).Exists) {
$pwshCIM = Get-CimInstance -Class CIM_DataFile -Filter ('Name="{0:s}"' -f $pwsh.Replace('\', '\\'))
if ($pwshCIM.Version -ge 7) {
Write-Output 'PowerShell 7 detected. Reinvoking with PowerShell 7...'
Start-Process -FilePath $pwsh -ArgumentList $MyInvocation.Line -WorkingDirectory $PWD
Start-Sleep 10
exit 0
}
} else {
Write-Output 'PowerShell 7 not detected. Please try again using PowerShell 7.'
Start-Sleep 10
exit 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment