Elevated current process unless executed privileged

$is_executed_privileged = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).
    IsInRole([Security.Principal.WindowsBuiltInRole]::"Administrator")
if (-not $is_executed_privileged) {
    if ((Get-Command wt.exe) -ne $null) {
        Start-Process wt "powershell -File $PSCommandPath -ExecutionPolicy Bypass" -Verb RunAs
    }
    else {
        Start-Process powershell "-File $PSCommandPath -ExecutionPolicy Bypass" -Verb RunAs
    }
    exit
}

The flag Run as Administrator is stored in byte 0x15 (= 21) at bit 0x20 (= 6).

Enable elevated execution for a file

$bytes = [System.IO.File]::ReadAllBytes((Resolve-Path $file))
$bytes[0x15] = $bytes[0x15] -bor 0x20 
[System.IO.File]::WriteAllBytes((Resolve-Path $file), $bytes)

Disable elevated execution for a file

$bytes = [System.IO.File]::ReadAllBytes((Resolve-Path $file))
$bytes[0x15] = $bytes[0x15] -bxor 0x20
[System.IO.File]::WriteAllBytes((Resolve-Path $file), $bytes)

Test whether this process is elevated

[bool] $isProcessElevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")

Require elevated execution

#Requires -RunAsAdministrator
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
 throw "Administrator privilege required to run this script"
}

Create a scheduled task

$actions = (New-ScheduledTaskAction -Execute 'powershell')
$principal = New-ScheduledTaskPrincipal -GroupId "BUILTIN\Administrators" -RunLevel Highest
$task = New-ScheduledTask -Action $actions -Principal $principal
Register-ScheduledTask 'Diagnostics' -InputObject $task

Sources:

Related:

Tags:
File System - Use paths, get meta data, link, download, and encrypt files and folders