Home > Back-end >  PowerShell date parsing not working in AD query
PowerShell date parsing not working in AD query

Time:01-20

I am trying to get a list of AD users whose account expired for more than 6 months.

Here is my code :

Get-ADUser -Filter {Enabled -eq $False} -Properties employeeID,sn,givenName,LastLogonDate | Where-Object {[STRING]$_.LastLogonDate -ne "" -and (Get-Date) -gt ([datetime]::parseexact([STRING]$_.LastLogonDate, "dd/MM/yyyy HH:mm:ss", $null)).AddMonths(6)} | select employeeID,sn,givenName,sAMAccountName,LastLogonDate | Sort-Object -Property sn | Export-Csv -Path $filename

I get the error : The DateTime represented by the string is not supported in the System.Globalization.GregorianCalendar

I also tried (Get-Culture) in parseexact. Doesn't work either.

While when simply executing something like [datetime]::parseexact("21/05/2015 16:14:37", "dd/MM/yyyy HH:mm:ss", $null) it works as expected.

What am I doing wrong ?

Thanks

CodePudding user response:

You can improve your query by adding LastLogonDate to the Filter and remove Where-Object:

$limit = [datetime]::Now.AddMonths(-6)
$params = @{
    Filter = "LastLogonDate -lt '$limit' -and Enabled -eq '$false'"
    Properties = 'LastLogonDate', 'sn', 'EmployeeID'
}

Get-ADUser @params | Sort-Object sn | Export-Csv .... 
  •  Tags:  
  • Related