Getting error when trying to format date

Occasional Visitor

Hi Everyone,

I have sourced a script to report on remote Windows servers for when they were last updated, but I seem to be getting an error for two servers only, all the others produce the desired results.

 

New-TimeSpan : Cannot bind parameter 'Start'. Cannot convert value "05/16/2022 08:42:38" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At :182 char:40
+ $DaySpan = New-TimeSpan -Start $InstalledOn -End $System
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-TimeSpan], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.NewTimeSpanCommand

 

Code that is indicated as failing

 

$System = (Get-Date -Format d)
$DaySpan = New-TimeSpan -Start $InstalledOn -End $System
$DaySpanDays = $DaySpan.Days

 

I have checked the region for all the servers, these two are no different to the others.

 

Thanks in advance.

1 Reply

@JagannathaSutaDas 

 

The error is pretty specific: it's saying it cannot automatically parse your value for $InstalledOn - which is a [string] - into a [datetime] object (which is what the -Start parameter expects to receive.)

 

You don't show how you're populating $InstalledOn but I suppose that doesn't really matter.

 

You might find this error is due to a different in regional settings. For example, the date you're retrieving is in US format (month, day, year) but perhaps the script is running on a system configured  for something a different region that uses the "day, month, year" format.

 

You can try that yourself. If this generates the same error:

 

 

[datetime]::Parse("05/16/2022 08:42:38")

 

 

But the following works, then it's a difference in region.

 

 

[datetime]::Parse("16/05/2022 08:42:38")

 

 

Example output from both the above commands.

LainRobertson_0-1656398941004.png

 

Still, once you've resolved this issue with $InstalledOn (there's multiple ways to resolve this), you're just going to run into another error since the assignment to $System on line one makes no sense when you look at how it's being used on line 2.

 

Here's one possible workaround for your issues. As I said above, I don't know how $InstalledOn is being populated so I'm simply assigning the text value from your error to it.

 

 

$InstalledOn = [datetime]::ParseExact("05/16/2022 08:42:38", "MM/dd/yyyy h:mm:ss", $null);
$System = Get-Date;
$DaySpan = New-TimeSpan -Start $InstalledOn -End $System;
$DaySpanDays = $DaySpan.Days;
$DaySpanDays;

 

 

Which produces the following output.

 

LainRobertson_1-1656399522345.png

 

Cheers,

Lain

 

Edited to correct a typo.