Last active
June 16, 2023 16:33
-
-
Save Jamesits/fea930ffbb8fb2db6ac480ddcd247e56 to your computer and use it in GitHub Desktop.
Pedantic mode in PowerShell
This file contains 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
# set -e (errexit) | |
$ErrorActionPreference = 'Stop' | |
$PSNativeCommandUseErrorActionPreference = $True | |
$ExecutionContext.InvokeCommand.PostCommandLookupAction = { | |
param([string]$command, [System.Management.Automation.CommandLookupEventArgs]$eventArgs); | |
if ($eventArgs.CommandOrigin -ne [System.Management.Automation.CommandOrigin]::Runspace) {return} | |
if ($eventArgs.Command.CommandType -eq [System.Management.Automation.CommandTypes]::Application) { | |
$cmd = $eventArgs.Command.Path | |
$eventArgs.CommandScriptBlock = { | |
Param([parameter(Position=0,ValueFromRemainingArguments=$true)][string]$arg); | |
$a = @{}; if ($arg) {$a["ArgumentList"] = $arg}; | |
$ret = Start-Process -FilePath $cmd -PassThru -NoNewWindow -Wait -WorkingDirectory (Get-Location).Path @a; | |
if ($ret.ExitCode -ne 0) {Write-Error "Exit code: $($ret.ExitCode)"}; | |
}.GetNewClosure() | |
$eventArgs.StopSearch = $True | |
} | |
} | |
# set -u (nounset) | |
# current scope | |
Set-StrictMode -Version Latest | |
# globally | |
Set-PSDebug -Strict | |
# set -x | |
Set-PSDebug -Trace 2 | |
# force UTF-8 | |
chcp 65001 | Out-Null | |
$PSDefaultParameterValues['*:Encoding'] = 'utf8' | |
# check for UAC elevation | |
#Requires -RunAsAdministrator | |
# UAC self-elevation | |
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { | |
$exe = ([System.Diagnostics.Process]::GetCurrentProcess()).MainModule.FileName | |
Start-Process -FilePath $exe -Verb RunAs -ArgumentList $MyInvocation.MyCommand.Definition -Wait | |
} | |
# Stop parsing arguments | |
--% | |
# ShellCheck | |
# https://www.powershellgallery.com/packages/PSScriptAnalyzer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment