Advertisement
Combreal

continueAdmScriptAfterReboot.ps1

Jun 16th, 2024
771
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function Test-Admin {
  2.     $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
  3.     $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
  4. }
  5.  
  6. If((Test-Admin) -eq $false)  {
  7.     Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
  8.     Exit
  9. }
  10.  
  11. $PSScriptName = Split-Path -Path $MyInvocation.MyCommand.Definition -Leaf
  12. $PSScriptFullPath = $MyInvocation.MyCommand.Definition
  13. $Scriptpath = Split-Path $MyInvocation.MyCommand.Path -Parent
  14. $ScriptName = $([io.path]::GetFileNameWithoutExtension($PSScriptName))
  15.  
  16. $TaskName = $ScriptName
  17. $TaskExists = Get-ScheduledTask -TaskName $TaskName -ErrorAction "SilentlyContinue"
  18.  
  19. If(-Not $TaskExists) {
  20.     $Trigger = New-ScheduledTaskTrigger -AtLogOn
  21.     $User = "NT AUTHORITY\SYSTEM"
  22.     $Action = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-Executionpolicy bypass -Noninteractive -File `"$PSScriptFullPath`""
  23.     Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -User $User -Action $Action -RunLevel "Highest" โ€“Force | Out-Null
  24.     Add-Content -Path "C:\Temp\whoami" -Value "$(whoami)"
  25.     Restart-Computer -Force
  26. }
  27. Else {
  28.     Add-Content -Path "C:\Temp\whoami" -Value "$(whoami)"
  29.     Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
  30.     Remove-Item -Path $PSScriptFullPath -Force
  31. }
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement