PowerShell:使用 Get-ADUserLastLogon 获取上次域登录
这篇博文中介绍的函数是我的 Active Directory 域服务部分工具的一部分,该工具已于 2018 年发布。一段时间后,我决定为我的工具的每个项目创建一个显式函数,供那些不感兴趣使用的人使用我的工具提供的不仅仅是查询域用户上次登录的功能。这是我的工具的第 16 项:查询 AD 用户上次登录。
获取 ADUserLastLogon
Get-ADUserLastLogon 获取 Active Directory 用户的上次登录时间戳。单独查询每个域控制器,以从所有 DC 的所有结果中计算最后一次登录。
该函数仅包含一个参数。提供用户登录名 (SamAccountName)。您还将看到哪个域控制器报告了用户的最新登录情况。
Get-ADUserLastLogon -UserLogonName patrick
如果输入不存在的用户名,则该函数终止。
如果没有用户的登录报告,该功能将显示以下消息。
该函数也适用于 PowerShell 7 及更高版本。
如果您喜欢,请查看我的下载部分以下载 *.ps1 文件或复制下面的代码。
代码
function Get-ADUserLastLogon {
# .SYNOPSIS
# Get-ADUserLastLogon gets the last logon timestamp of an Active Directory user.
# .DESCRIPTION
# Each domain controller is queried separately to calculate the last logon from all results of all DCs.
# .PARAMETER
# UserLogonName
# Provide the user logon name (samaccountname) of the user.
# .EXAMPLE
# Get-ADUserLastLogon -UserLogonName s.stollane
# .NOTES
# Author: Patrick Gruenauer
# Web:
# https://sid-500.com
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)]
$UserLogonName
)
$resultlogon=@()
Import-Module ActiveDirectory
$ds=dsquery user -samid $UserLogonName
If ($ds) {
$getdc=(Get-ADDomainController -Filter *).Name
foreach ($dc in $getdc) {
Try {
$user=Get-ADUser $UserLogonName -Server $dc -Properties lastlogon -ErrorAction Stop
$resultlogon+=New-Object -TypeName PSObject -Property ([ordered]@{
'User' = $user.Name
'DC' = $dc
'LastLogon' = [datetime]::FromFileTime($user.'lastLogon')
})
}
Catch {
''
Write-Warning "No reports from $($dc)!"
}
}
$resultlogon | Where-Object {$_.lastlogon -NotLike '*1601*'} | Sort-Object LastLogon -Descending | Select-Object -First 1 | Format-Table -AutoSize
If (($resultlogon | Where-Object {$_.lastlogon -NotLike '*1601*'}) -EQ $null)
{
''
Write-Warning "No reports for user $($user.name). Possible reason: No first login."
}
}
else
{throw 'User not found. Check entered username.'}
}
如何使用它
将上面的代码复制到 PowerShell ISE (ise.exe) 或您选择的编辑器中并运行代码。然后输入命令并享受它的乐趣。
如果要使该函数永久可用,以便每次启动 PowerShell 时该函数都可用,则必须在 C:\Program Files\WindowsPowerShell\Modules 中创建一个文件夹。将文件夹命名为 Get-ADUserLastLogon。然后将代码另存为该文件夹中的 .psm1 文件。下面的屏幕截图将为您提供帮助。




