简体   繁体   中英

PowerShell 7; String to DateTime?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM