Powershell脚本来查找用户自上次重新启动以来是否已经login

所以我一直在研究Powershell脚本,它需要检测自上次重新启动以来是否发生了交互式login。 在启动任务之前,我可以强制系统重新启动,但是我想为脚本添加一些智能。

注意事项:

  • 必须使用Powershell。
  • 不需要特殊的电源组件或插件。
  • 不能使用Active Directory命令。 (没有get-qaduser)

我能够得到最后一次系统已经重新启动:

$date = Get-WmiObject Win32_OperatingSystem | %{$_.LastBootUpTime} $RebootTime = [System.DateTime]::ParseExact($date.split(".")[0],'yyyyMMddHHmmss',$null) 

有任何想法吗? 提前致谢

如果你设置使用WMI,你可以得到一个更干净的LastBootUpTime

 PS C:\> $wmi = Get-WmiObject -Class Win32_OperatingSystem PS C:\> $rebootTime = $wmi.ConvertToDateTime($wmi.LastBootUpTime) PS C:\> $rebootTime Tuesday, May 24, 2011 3:18:28 PM 

考虑到这一点,我们searchSecurity事件日志,自$rebootTime ,为最新的, 成功的 $rebootTime 4624包含Logon Type 2 – 交互式login:

 PS C:\> $entry = Get-EventLog -After $rebootTime -LogName Security | Where-Object {($_.EventID -eq '4624') -and ($_.EntryType -eq 'SuccessAudit') -and ($_.Message | Select-String "Logon Type:\t\t\t2")} | Select-Object -First 1 PS C:\> $lastLogon = $entry.TimeGenerated PS C:\> $lastLogon Tuesday, May 24, 2011 3:19:34 PM 

然后,快速比较一下:

 PS C:\> $lastLogon -gt $rebootTime True 

上面的代码可以被转储到脚本中和/或在远程计算机上执行。 我只交互地运行这些命令来演示示例输出。