Powershell to forcibly log a user off

Recently, a shared PC has been left logged in as a user which is not ideal. I wondered if there was anyway that powershell could get a user’s idle time, but after failing to find how to do this I decided to just do an enforced logoff after a set period (tho’ “(get-wmiobject win32_operatingsystem).Win32Shutdown(0)” is actually a normal logoff; (get-wmiobject win32_operatingsystem).Win32Shutdown(4) would be the forced version))

It’s harsh, but this script logs someone off after 2 hours, basically by keeping their login time as one variable then comparing it to a time variable that is updated every 30 seconds. It also stops some services, but bear in mind that for this bit to work you have to be running the script “As Administrator”. Fortunately, Windows task scheduler allows tasks to be run at logon and “As Administrator”.

===================

$atLogon = get-date -displayhint time

do {

$now = get-date -displayhint time
$difference = $now – $atLogon

if ($difference.minutes -eq 120)
{
#Define hub transport server
$smtp_server = “you-mail-server-your-domain.com”

#Define email sender and recipient
$sender = “Your Sender your.sender@yourdomain.com
$recipient = “Your Recipient your.recipient@yourdomain.com

#Define email subject and body
$msg_subject = “Some PC xxx”
$msg_body_text = “Some PC xxx has been logged off at $now”

#Send it
Send-MailMessage -to $sender -from $recipient -subject $msg_subject -body $msg_body_text -smtpserver $smtp_server

# Writing an event
$EventLog = New-Object System.Diagnostics.EventLog(‘Application’)
$EventLog.MachineName = “.”
$EventLog.Source = “your Event”
$EventLog.WriteEntry(“Now stopping SomeService”,”Information”, $EventID)

stop-service “SomeService” -force
start-service “SomeService”

(get-wmiobject win32_operatingsystem).Win32Shutdown(0)
}

if ($difference.minutes -eq 115)
{
$MsgBox = New-Object -ComObject wscript.shell
$MsgBox.Popup(“Reminder: you will be logged off in 5 minutes. Service “SomeService” will also be restarted.”)

}

if ($difference.minutes -eq 90)
{
$MsgBox = New-Object -ComObject wscript.shell
$MsgBox.Popup(“Reminder: you will be logged off in 30 minutes.”)
}

if ($difference.minutes -eq 60)
{
$MsgBox = New-Object -ComObject wscript.shell
$MsgBox.Popup(“Reminder: you will be logged off in 1 hour.”)
}

Start-Sleep -Seconds 30

} while ($true)

=================

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s