Get idle time of machine

后端 未结 3 553
我在风中等你
我在风中等你 2020-12-15 06:25

Is there a way to get the idle time of the machine, as in the amount of time the machine has not been used for, in minutes/hours using Powershell or a batch file?

3条回答
  •  再見小時候
    2020-12-15 06:34

    Here's a PowerShell solution that uses the Win32 API GetLastInputInfo.

    Add-Type @'
    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    
    namespace PInvoke.Win32 {
    
        public static class UserInput {
    
            [DllImport("user32.dll", SetLastError=false)]
            private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
    
            [StructLayout(LayoutKind.Sequential)]
            private struct LASTINPUTINFO {
                public uint cbSize;
                public int dwTime;
            }
    
            public static DateTime LastInput {
                get {
                    DateTime bootTime = DateTime.UtcNow.AddMilliseconds(-Environment.TickCount);
                    DateTime lastInput = bootTime.AddMilliseconds(LastInputTicks);
                    return lastInput;
                }
            }
    
            public static TimeSpan IdleTime {
                get {
                    return DateTime.UtcNow.Subtract(LastInput);
                }
            }
    
            public static int LastInputTicks {
                get {
                    LASTINPUTINFO lii = new LASTINPUTINFO();
                    lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
                    GetLastInputInfo(ref lii);
                    return lii.dwTime;
                }
            }
        }
    }
    '@
    

    And an example usage:

    for ( $i = 0; $i -lt 10; $i++ ) {
        Write-Host ("Last input " + [PInvoke.Win32.UserInput]::LastInput)
        Write-Host ("Idle for " + [PInvoke.Win32.UserInput]::IdleTime)
        Start-Sleep -Seconds (Get-Random -Minimum 1 -Maximum 5)
    }
    

提交回复
热议问题