New-TimeSpan error suppress

I’m writing a script to send out email alerts to users if their domain accounts are expiring in 5 days or less. It is working, except on some of the service accounts, I’m getting the following error. How can I suppress this from showing? I tried -ErrorAction SilentlyContinue and also Ignore, but these errors still show up.

New-TimeSpan : Cannot bind parameter 'Start' to the target. Exception setting "Start": "Cannot convert null to type 
"System.DateTime"."
At C:\Users\t.antonyadmin\Desktop\User_PW_Email_Alert.ps1:11 char:42
+     $days_elapsed = (New-TimeSpan -Start $user_last_pw_set -End $toda ...
+                                          ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (:) [New-TimeSpan], ParameterBindingException
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.PowerShell.Commands.NewTimeSpanCommand

If you want to ignore all errors in a script, you can use the system variable $ErrorActionPreference and do the same thing: $ErrorActionPreference= 'silentlycontinue'

Thank you, that worked. So my question is, why didn’t that work when I added -ErrorAction -SilentlyContinue at the end of my string?

1 Like

A more professional solution would be to understand where the error comes from and avoid it in the first place. If that’s not possible it would be better to handle the error gracefully with a try catch block.

Here you can read more about :

Regardless of that - you do not show you code so we can only guess what the actually problem is.
I’d expect it to be pretty likely that your service accounts to not have password aging activated. So maybe there is no $user_last_pw_set?! :wink:

-ErrorAction is a common parameter for cmdlets and advanced functions. You don’t apply them to strings. Perhaps if you show your whole example line that errors, we could answer your question.