Last active
December 9, 2024 07:08
-
-
Save AfroThundr3007730/d51311cdd9b5adaa8e53256768e8fe53 to your computer and use it in GitHub Desktop.
Guard functions for powershell version and elevation level
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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