Jerry1
Jerry1

Reputation: 372

PowerShell's Get-Date and "Cannot bind parameter 'Date' to the target"

I am very confused of this error message:

Get-Date : Cannot bind parameter 'Date' to the target. Exception setting "Date": "Object reference not set to an instance of an object."

The problem line is:

$logondate = $(Get-Date $([datetime]::Parse( $user.LastLogonDate)) -Format 'yyyy-MM-dd HH:mm:ss')

# User is vartype: System.Management.Automation.PSMethod
#$user.LastLogonDate in debug with this value: 10.06.2014 14:26:13 (dd.MM.yyyy)

What does this error mean?

From 30 AD accounts there are only three with this ParameterBindingException.

Full error message:

Get-Date : Cannot bind parameter 'Date' to the target. Exception setting "Date": "Object reference not set to an instance of an object."
At C:\scripts\AD.ps1:309 char:28
+     $logondate = $(get-date <<<<  $([datetime]::Parse( $user.LastLogonDate)) -Format 'yyyy-MM-dd HH:mm:ss')
    + CategoryInfo          : WriteError: (:) [Get-Date], ParameterBindingException
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.PowerShell.Commands.GetDateCommand

Upvotes: 1

Views: 10647

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

You get that error, because for some reason Parse() cannot parse $user.LastLogonDate into a date. Perhaps because the user never logged on (so the value is $null), or because Parse() doesn't recognize the default date format.

However, the LastLogonDate property (as created by Get-ADUser) already holds a DateTime value. What you're trying to do here is: implicitly convert the date to a string, parse that string back into a date, then create a formatted string from it again.

Don't.

Simply format the DateTime value you already have:

PS C:\> $user = Get-ADUser $env:USERNAME -Property *
PS C:\> $user.LastLogonDate.GetType().FullName
System.DateTime
PS C:\> $user.LastLogonDate

Monday, July 11, 2014 8:50:38 AM

PS C:\> $user.LastLogonDate.ToString('yyyy-MM-dd HH:mm:ss')
2014-07-07 08:50:38

Add a check for $null values to prevent errors for users that never logged on:

if ($u.LastLogonDate -ne $null) {
    $user.LastLogonDate.ToString('yyyy-MM-dd HH:mm:ss')
}

Upvotes: 2

Related Questions