Home > front end >  Handling Date in Power-Shell JSON Object
Handling Date in Power-Shell JSON Object

Time:10-19

I am trying to get user info based on LastLogondate from AD. I am converting final output in JSON format.

Here the small script to handle dates. Actually I am passing $PasswordAge as LastLogonDate of the user.

 $PasswordAge = (Get-Date).AddDays(-60) # This is actually LastLogonDate from user info
$CurrentDate = (Get-Date)
#Write-Host $PasswordAge
try
{
$LastLogonDays = (New-TimeSpan -Start $PasswordAge -End $CurrentDate).Days
#Write-Host $LastLogonDays
}
catch{
$Message = $_.Exception.Message
}

$JSONOutput = @{"result"=$LastLogonDays;"error"=$Message} | ConvertTo-Json #-Compress
Write-Output $JSONOutput 

Receiving below error if I use ConvertTo-Json and print output. Day difference is correct but every-time getting message in error

 {
    "error":  "Cannot bind parameter \u0027Start\u0027 to the target. Exception setting \"Start\": \"Cannot convert null to type \"System.DateTime\".\"",
    "result":  60
} 

Thank for your help in advance.

CodePudding user response:

New-TimeSpan sucks. I almost always get the same error. It's reported that the issue stems from a mismatch of the culture (language) settings on your OS, the format your OS is configured to use for dates and times, and the format the DateTime object is actually in. I live in the US, use the English language, and use our standard format for dates and I still have this problems with getting New-TimeSpan to function. I've long-since given up on getting this cmdlet to work consistently.

Fortunately there's an easy workaround; just subtract two datetimes to get a System.TimeSpan instead. Works every time.

$LastLogonDays = ( $CurrentDate - $PasswordAge ).Days
  • Related