我試圖從 AD 獲取基于 LastLogondate 的用戶資訊,并根據 LastLogonDate 和 Current Date 計算出自用戶登錄以來的天數。
這是腳本
$Result = Get-ADUser -filter {SamAccountName -eq 'username'} -Properties UserPrincipalName, mail, LastLogonDate, Enabled
$CurrentDate = (Get-Date)
Write-Host $Result.LastLogonDate
try
{
$LastLogonDays = ($CurrentDate - $Result.LastLogonDate).Days
Write-Host $LastLogonDays
$Json = @{
"UserPrincipalName"= $Result.UserPrincipalName;
"mail"= $Result.mail;
"LastLogonDate"= ($Result.LastLogonDate).ToString();
"days"= $LastLogonDays
}
$User = $Json
}
catch{
$Message = $_.Exception.Message
}
$JSONOutput = @{"result"=$User;"error"=$Message} | ConvertTo-Json #-Compress
Write-Output $JSONOutput
我得到了預期的結果,但日志中也捕獲了錯誤,無法弄清楚錯誤發生的原因/方式
8/18/2021 4:16:45 AM
61
{
"error": "Cannot find an overload for \"op_Subtraction\" and the argument count: \"2\".",
"result": {
"LastLogonDate": "8/18/2021 4:16:45 AM",
"mail": "[email protected]",
"UserPrincipalName": "UserPrincipalName",
"days": 61
}
}
uj5u.com熱心網友回復:
要解釋為什么您會收到該錯誤:
PS > [datetime]::Now - $null
Cannot find an overload for "op_Subtraction" and the argument count: "2".
這意味著,此用戶或此用戶之前的用戶$null對其LastLogonDate財產具有價值。請注意,由于您處理代碼的方式,我在此之前說的是用戶,變數上的值$Message永遠不會被清除,并且您總是在此處添加它的值:
$JSONOutput = @{"result"=$User;"error"=$Message}
現在,作為替代方案,這就是我個人處理代碼的方式。請注意,try { } catch { }在這種情況下我沒有使用塊,因為我覺得不需要它。
$ErrorActionPreference = 'Stop'
$CurrentDate = [datetime]::Now
$userName = 'john.doe'
# UserPrincipalName and Enabled are not needed. Both are default properties returned by Get-ADUser
$Result = Get-ADUser -LDAFilter "(SamAccountName=$userName)" -Properties mail, LastLogonDate
if(-not $Result)
{
throw "No user found with sAMAccountName $userName"
}
Write-Host $Result.LastLogonDate
$Json = @{
UserPrincipalName = $Result.UserPrincipalName
mail = $Result.mail
}
if($Result.LastLogonDate)
{
$LastLogonDays = ($CurrentDate - $Result.LastLogonDate).Days
Write-Host $LastLogonDays
$Json.LastLogonDate = $Result.LastLogonDate.ToString()
$Json.Days = $LastLogonDays
}
else
{
$Json.Error = "Null value on LastLogonDate for User {0}" -f $Result.Name
}
$Json | ConvertTo-Json
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/323304.html
