Skip to content

Instantly share code, notes, and snippets.

@SadProcessor
Created April 19, 2023 20:05
Show Gist options
  • Save SadProcessor/bbe24658cba0d2ba022e76a5991604d9 to your computer and use it in GitHub Desktop.
Save SadProcessor/bbe24658cba0d2ba022e76a5991604d9 to your computer and use it in GitHub Desktop.
function Invoke-AsTrustedInstallerJob{
[Alias('TIJob')]
Param(
[Parameter()][Scriptblock]$Scriptblock,
[Parameter()][String]$UserID=$("$Env:ComputerName\$Env:UserName"),
[Parameter()][String]$TaskName='TIJob'
)
# IsAdmin??
$IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if(-Not$IsAdmin){Write-Warning "Must be admin";Return}
# Default/test
if(-Not$Scriptblock){
$Scriptblock = {[PSCustomObject]@{
IsName = $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name).split('\')[1]
IsAdmin = $(New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
IsSystem = $([System.Security.Principal.WindowsIdentity]::GetCurrent().IsSystem)
IsTI = $([System.Security.Principal.WindowsIdentity]::GetCurrent().groups.value -contains "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464")
} | export-Csv C:\Users\TIJob.txt -NoTypeInformation -Force
}}
# Run as TI
$Jobs = '\Microsoft\Windows\PowerShell\ScheduledJobs'
$SP = New-ScheduledTaskPrincipal -UserId $UserId -RunLevel Highest
$Null = Register-ScheduledJob -Name $taskName -ScriptBlock $ScriptBlock
$Null = Set-ScheduledTask -TaskPath $Jobs -TaskName $taskName -Principal $SP
$svc = New-Object -ComObject 'Schedule.Service'; $svc.Connect()
$Tsk = ($svc.GetFolder($Jobs)).GetTask($TaskName)
$Null = $tsk.RunEx($null,0,0,'NT SERVICE\TrustedInstaller')
while($tsk.state -ne 3){Sleep -m 500}; $tsk.Stop(0)
Unregister-ScheduledJob $TaskName -Confirm:$false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment