Skip to content

Instantly share code, notes, and snippets.

@Jamesits
Last active June 16, 2023 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jamesits/fea930ffbb8fb2db6ac480ddcd247e56 to your computer and use it in GitHub Desktop.
Save Jamesits/fea930ffbb8fb2db6ac480ddcd247e56 to your computer and use it in GitHub Desktop.
Pedantic mode in PowerShell
# 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