2

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".
mklement0
  • 382,024
  • 64
  • 607
  • 775
Paddy
  • 123
  • 7

1 Answers1

3

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]
zett42
  • 25,437
  • 3
  • 35
  • 72
  • You've got to be kidding me. Took me hours, and you solved it in a matter of minutes. THANK YOU @zett42 ! – Paddy Jun 19 '22 at 18:12
  • 2
    @Paddy You are welcome. I just entered `$result.Headers['Last-Modified'].GetType().Name` to confirm what I suspected from the error message. – zett42 Jun 19 '22 at 18:14