用于检查Active Directory用户上次登录的Powershell脚本

问题描述 投票:0回答:2

我正在尝试编写一个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"
}
powershell authentication
2个回答
1
投票

有分别使用Get-ADUserGet-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"
}

0
投票

当您使用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

编辑:

你的代码还有一些问题:

  1. 您需要删除displaylastlogon
  2. 你不能使用-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)
© www.soinside.com 2019 - 2024. All rights reserved.