Skip to content

Instantly share code, notes, and snippets.

@NathanTheGr8
Created March 10, 2020 16:53
Show Gist options
  • Save NathanTheGr8/780f96eeefb1c35a908fd979b999f7db to your computer and use it in GitHub Desktop.
Save NathanTheGr8/780f96eeefb1c35a908fd979b999f7db to your computer and use it in GitHub Desktop.
Param(
[Parameter(Mandatory = $True)]
[string[]]$UserIDs,
[Parameter(Mandatory = $True)]
[int]$Duration
)
foreach ($UserID in $UserIDs) {
$GrantAdminTo = "Domain\" + $UserID
if (($Duration -eq 0) -and ((Get-ScheduledTask "Remove Admin Access $UserID" -ErrorAction SilentlyContinue) -ne $null )) {
Unregister-ScheduledTask -TaskName 'Remove Admin Access $UserID' -confirm:$false
Out-File -FilePath 'C:\windows\logs\Software\Admin.log' -InputObject ((Get-Date).ToString() + ' | Removed Task | ' + $GrantAdminTo) -Append
}
Add-LocalGroupMember -Group "Administrators" -Member "$GrantAdminTo" -ErrorAction SilentlyContinue
if (!(Test-Path 'c:\windows\logs\Software'))
{ New-Item 'c:\windows\logs\Software' -ItemType Directory -Force }
#Validates user is memeber of Admin Group & logs message
if ((Get-LocalGroupMember -Group "Administrators" -Member "$GrantAdminTo" -ErrorAction SilentlyContinue).count -gt 0) {
if ($Duration -gt 0)
{ Out-File -FilePath 'C:\windows\logs\Software\Admin.log' -InputObject ((Get-Date).ToString() + " | Added | $GrantAdminTo | Until: $((get-date).AddDays($Duration).ToString())") -Append }
else
{ Out-File -FilePath 'C:\windows\logs\Software\Admin.log' -InputObject ((Get-Date).ToString() + " | Added | $GrantAdminTo | Until: Indefinite") -Append }
}
else {
Out-File -FilePath 'C:\windows\logs\Software\Admin.log' -InputObject ((Get-Date).ToString() + " | ERROR | $GrantAdminTo | USER DOES NOT EXIST, UNABLE TO ADD USER TO ADMIN GROUP") -Append
RETURN "BAD USERNAME"
}
if ($Duration -gt 0) {
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument "-NoProfile -WindowStyle Hidden -command `"`& {`$Member = '$GrantAdminTo';Remove-LocalGroupMember -Group Administrators -Member `$Member; Unregister-ScheduledTask -TaskName 'Remove Admin Access $UserID' -confirm:`$false; `$Cleared = (Get-Date).ToString() + ' | Removed | ' + `$Member; Out-File -FilePath 'C:\windows\logs\Software\Admin.log' -InputObject `$Cleared -Append}`""
$Settings = New-ScheduledTaskSettingsSet -DeleteExpiredTaskAfter 10
$Date = ((get-date).AddDays($Duration))
$trigger = New-ScheduledTaskTrigger -Once -At $Date -RepetitionInterval (New-TimeSpan -Hours 3) -RepetitionDuration (New-TimeSpan -Days 30)
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Remove Admin Access $UserID" -Description "Remove Admin Access" -User 'NT AUTHORITY\SYSTEM' -RunLevel Highest -Force -Settings $Settings
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment