Search code examples
powershellactive-directoryquest

You cannot call a method on a null-valued expression - What is it and how do I fix it?


I'm busy creating a query which will identify users whose passwords are about to expire.

I am however running into a slight error in my query; it seems to return the correct results, but throws an error 5 times, which seems to correspond with 5 user accounts.

The error I get is;

You cannot call a method on a null-valued expression.
At C:\common\SCRIPTS\PASSWORD_EXPIRY_CUSTOM.ps1:9 char:116
+ ... ires | where { $_.PasswordExpires -gt $null -and `
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

The only difference I can see in the accounts it gets stuck on is the fact they are set to change their passwords at next login, therefore the PasswordExpires attribute is actually $null, but even filtering this out doesn't seem to fix the error.

The code I am running:

$date = Get-Date

$FirstWarning = $date.AddDays(2).ToShortDateString()
$SecondWarning = $date.AddDays(7).ToShortDateString()
$LastWarning = $date.AddDays(15).ToShortDateString()



$Users = Get-QADUser -SizeLimit 0 -SearchRoot 'mydomain.com/users' -IncludedProperties PasswordExpires | 
             Where { 
                 $_.PasswordExpires -gt $null -and `
                ($_.PasswordExpires).ToShortDateString() -eq "$FirstWarning" -or `
                ($_.PasswordExpires).ToShortDateString() -eq "$SecondWarning" -or `
                ($_.PasswordExpires).ToShortDateString() -eq "$LastWarning" 
             }

Can someone help me out here please? I'm about to pull my hair out; even though it's likely a simple solution.


Solution

  • Why is sizeLimit = 0?

    " -SizeLimit Maximum number of items to be returned (default=1000) "

    That could result in $null being piped to your processing section, which then exposes an error. I think it needs parentheses to surround the 'or' clauses. Also I would replace "-gt $null" with "-ne $null".

    $Users = Get-QADUser -SizeLimit 0 -SearchRoot 'mydomain.com/users' -IncludedProperties PasswordExpires | where { $_.PasswordExpires -ne $null -and `
    ( `
      ($_.PasswordExpires).ToShortDateString() -eq "$FirstWarning" -or `
      ($_.PasswordExpires).ToShortDateString() -eq "$SecondWarning" -or `
      ($_.PasswordExpires).ToShortDateString() -eq "$LastWarning" `
    ) `
    }