簡體   English   中英

Powershell腳本,用於檢查Active Directory用戶是否最后登錄

[英]Powershell Script to check if Active Directory User Last Logon

我正在嘗試編寫一個Powershell腳本,該腳本接受用戶名作為參數,並顯示用戶的上次登錄時間。 如果用戶之前has not logged in before則應顯示該消息has not logged in before

例如,如果您運行.\\lastlogon -username marywong ,則顯示消息:

marywong上次登錄時間13/07/2017

如果您運行.\\lastlogon -username guest.\\lastlogon -username 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-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"
}

當您使用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,因為它將始終為false。.用戶將來無法登錄..您需要使用-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不為null

將if更改為此:

if($lastlogontime -ne $null -and $lastlogontime -lt $time)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM