用于检查Active Directory用户上次登录的Powershell脚本
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用于检查Active Directory用户上次登录的Powershell脚本相关的知识,希望对你有一定的参考价值。
我正在尝试编写一个powershell脚本,它接受用户名作为参数,并显示用户的上次登录时间。如果用户之前未登录,则应显示消息has not logged in before
。
例如,如果您运行.lastlogon -username marywong
,则会显示以下消息:
marywong last logon time 13/07/2017
如果你运行.lastlogon -username guest
,我收到消息:
guest还没有登录
下面是我的代码,但是当用户之前没有登录时,它似乎没有循环到else循环中。
param (
[string]$username
)
$user = Get-ADUser -Filter {sAMAccountName -eq $username} | Get-ADObject -Properties lastLogon
$lastlogontime = $user.lastlogon
If ($user -ne $Null) {
if($user.LastLogon -gt $time) {
$displaylastlogon = [datetime]::FromFileTime($lastlogontime)
Write-Host $username " last logon time" $displaylastlogon
}
else {
$displaylastlogon = [datetime]::FromFileTime($lastlogontime)
Write-Host $username " has not logged in before"
}
}
else {
Write-Host $username " does not exist"
}
有分别使用Get-ADUser
和Get-ADObject
可以获得的信息。如果用户从未登录,则他们仍然是存在的用户。这与不存在的用户不同。
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true, Position = 0)]
[string]$username
)
$user = Get-ADUser -Filter {SamAccountName -eq $username}
if ($user -ne $null) {
$userlogon = $user | Get-ADObject -Properties lastLogon
if ($userlogon.LastLogon -ne $null) {
$lastlogontime = [DateTime]::FromFileTime($userlogon.LastLogon)
Write-Host $username " last logon time" $lastlogontime
} else {
Write-Host $username " has not logged in before"
}
} else {
Write-Host $username " does not exist"
}
当您使用lastLogon时,您将获得AD使用的格式...然后当if运行时,您将获得
Could not compare "131820853335016078" to "09/24/2018 18:18:57". Error: "Cannot convert value "9/24/2018 6:18:57 PM" to type "System.Int64". Error: "Invalid cast from 'DateTime' to 'Int64'.""
所以它没有到达其他地方..
尝试使用LastLogonDate属性,它将为您提供更多帮助。
试着用这个:
$user = Get-ADUser -Filter {sAMAccountName -eq $username} -Properties LastLogonDate
$lastlogontime = $user.lastlogonDate
编辑:
你的代码还有一些问题:
- 您需要删除displaylastlogon
- 你不能使用-gt因为它总是假的..用户将来无法登录..你需要使用-lt
这是完整的脚本,工作:
$user = Get-ADUser -Filter {sAMAccountName -eq $username} -Properties LastLogonDate
$lastlogontime = $user.lastlogonDate
If ($user -ne $Null) {
if($lastlogontime -lt $time)
{
Write-Host $username " last logon time" $lastlogontime
}
else
{
Write-Host $username " has not logged in before"
}
}
else
{
Write-Host $username " does not exist"
}
另一个编辑:
我只是注意到当用户从未登录时它没有回答这种情况,因为你将获得$ null并且$ null低于当前时间。所以你需要检查lastlogontime是否为空
将if更改为:
if($lastlogontime -ne $null -and $lastlogontime -lt $time)
以上是关于用于检查Active Directory用户上次登录的Powershell脚本的主要内容,如果未能解决你的问题,请参考以下文章
在 Java 应用程序中检查使用 Active Directory 登录的用户
使用 Powershell 清理孤立的 Active Directory 用户配置文件文件夹
根据 Active Directory 策略检查密码 [重复]