I'm working on a shutdown script to power off machines that have been idle for over 2 hours. Currently, it logs idle time but doesn't seem to be accurate. Recently, it mistakenly shut down machines that were actively in use. I believe the issue might stem from users accessing the machines primarily through Citrix Workspace, which could be affecting the idle time detection. Here's the code I'm using, and I'm looking for advice on how to improve it!
4 Answers
What exactly do you consider "idle"? If someone is running a long process, your script might inadvertently kick them out if they’re not interacting with the machine during that time.
You might want to track mouse movements within a set timeframe to determine idleness better. Check this adapted code snippet out:
```powershell
Add-Type @"
using System;
using System.Runtime.InteropServices;
public static class IdleTime {
[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[StructLayout(LayoutKind.Sequential)]
struct LASTINPUTINFO {
public uint cbSize;
public uint dwTime;
}
public static uint GetIdleTime() {
LASTINPUTINFO lii = new LASTINPUTINFO();
lii.cbSize = (uint)Marshal.SizeOf(lii);
GetLastInputInfo(ref lii);
return ((uint)Environment.TickCount - lii.dwTime) / 1000;
}
}
"@
$threshold = 600 # seconds (10 minutes)
while ($true) {
$idle = [IdleTime]::GetIdleTime()
if ($idle -ge $threshold) {
Write-Host "Idle for $threshold seconds — shutting down..."
Stop-Computer -Force
break
}
Start-Sleep -Seconds 10
}
```
This should help limit shutdowns to truly idle machines!
No problem, glad I could help!
Are you replicating what the operating system already handles with its power settings? Keep in mind that users might not be interacting directly with their PCs due to ongoing processes, updates, or software installations. Just relying on mouse and keyboard interactions might not capture active usage accurately.
Consider checking the session info from your Delivery Controllers regarding specific Delivery Groups. If you're connected, you can command Citrix to shut down any offending VMs—but make sure you really want to shut down the machines themselves and not just the VMs they're accessing.
I didn't want to shut down the VMs, just the machines connecting to them. But thanks for the input!

That works perfectly, thanks a lot! 🙂