Temporary Admin Access with PowerShell
Every IT administrator has faced the challenge of granting users temporary administrator rights. This might be necessary for instances when users are traveling and may need to install software or troubleshoot issues on their company computers. While this can be a necessity, it’s also a potential security risk. The trick is to provide admin rights in a controlled and temporary manner.
In this blog post, we’ll walk you through a PowerShell script that accomplishes exactly that. This script grants a user administrator access for a specified number of days and then automatically revokes the access when the time period expires.
Prerequisites
To run the script, you need to have PSexec.exe from Windows Sysinternals installed on your host computer. This utility lets you execute processes on remote systems. You can download it here.
The Script
$CompName = Read-Host('Computer Name to add as admin x day.');
$days = Read-Host('How many days');
$Date=(get-date).AddDays($days)
$DateYear=$Date.ToString("yyyy")
$DateMonth=$Date.ToString("MM")
$DateDay=$Date.ToString("dd")
$DateHour=$date.ToString("HH")
$DateMinute=$date.ToString("mm")
$DateString=$DateYear + '/' + $DateMonth + '/' + $DateDay
$TimeString=$DateHour + ':' + $DateMinute
$PSString1='psexec.exe \\' + $CompName + ' -s cmd.exe "/c net localgroup administrators /add interactive"'
$PSString2='psexec.exe \\' + $CompName + ' -s cmd.exe "/c schtasks /create /tn RemoveInteractiveAsAdmin /SC once /ru system /tr "net localgroup administrators /del interactive" /sd ' + $DateString + ' /st ' + $TimeString + ' /f"'
if (Test-Connection -computername $CompName -count 1 -quiet)
{
Invoke-Expression $PSString1
Invoke-Expression $PSString2
}
else {$Popup.Popup("Error, can not ping $CompName",0,"Error",16)}
The script utilizes Read-Host to take in two user inputs: the computer name and the number of days for which admin rights should be granted.
$CompName = Read-Host('Computer Name to add as admin x day.');
$days = Read-Host('how many days');
Wrapping Up
This script simplifies the process of providing users with temporary administrative rights on their company computers. It allows IT administrators to safely give users the access they need while ensuring that this access is revoked automatically after a specific period.
As always, it’s important to remember that even temporary administrative rights can be a significant security risk if misused. Therefore, only grant such access to users you trust, and monitor the system during the period they have this access.
Buy Me a Coffee