是否有一种方法可以使用Powershell或批处理文件来获取机器的空闲时间,如机器未使用的时间,以分钟/小时为单位?
发布于 2013-04-06 12:09:14
下面是一个使用Win32 API GetLastInputInfo的PowerShell解决方案。
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;
}
}
}
}
'@
下面是一个用法示例:
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)
}
发布于 2014-04-08 12:20:39
$Last = [PInvoke.Win32.UserInput]::LastInput
$Idle = [PInvoke.Win32.UserInput]::IdleTime
$LastStr = $Last.ToLocalTime().ToString("MM/dd/yyyy hh:mm tt")
Write-Host ("Last user keyboard/mouse input: " + $LastStr)
Write-Host ("Idle for " + $Idle.Days + " days, " + $Idle.Hours + " hours, " + $Idle.Minutes + " minutes, " + $Idle.Seconds + " seconds.")
试试这个--尽管它是远程运行的,但它可能在不同的会话上运行,因此有不同的空闲时间?
https://stackoverflow.com/questions/15845508
复制相似问题