This piece of code works fine in PowerShell 5.
It returns the following date/time, depending on which OS and OS language is used;
"Wed, 04 Mar 2015 07:39:54 GMT"
"woensdag 4 maart 2015 08:39:54"
However, in PowerShell 7 it no longer works and gives me the following error. I've spent hours online to see what happens, but .. Whatever I try, it never works. How can I transform a String in a DateTime object in PowerShell 7.2.4?
$result = Invoke-WebRequest -Method HEAD -Uri "https://microsoft.com" -UseBasicParsing -ErrorAction:Stop -TimeoutSec 30
$LastModifiedDateTime = [DateTime] $result.Headers['Last-Modified']
InvalidArgument: Cannot convert the "System.String[]" value of type "System.String[]" to type "System.DateTime".
In PowerShell 7.x the type of the header fields has changed from String
to String[]
, that is an array of strings.
So just take the first element of the array to let the conversion succeed:
$LastModifiedDateTime = [DateTime] $result.Headers['Last-Modified'][0]