Powershell 7;字符串到DateTime?

发布于 2025-02-08 22:16:01 字数 594 浏览 1 评论 0原文

该代码在PowerShell 5中正常工作。 它返回以下日期/时间,具体取决于使用哪种OS和OS语言; “ 2015年3月4日,星期三07:39:54 GMT”
“ Woensdag 4 Maart 2015 08:39:54”

但是,在PowerShell 7中,它不再有效,并给我带来以下错误。我已经在网上花了几个小时来看看会发生什么,但是..无论我尝试什么,它都永远无法使用。 如何在PowerShell 7.2.4中的DateTime对象中转换字符串?

$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".

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".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

药祭#氼 2025-02-15 22:16:01

在PowerShell 7.x中,标题字段的类型已从String更改为string [],这是字符串数组。

因此,只需以阵列的第一个元素让转换成功:

$LastModifiedDateTime = [DateTime] $result.Headers['Last-Modified'][0]

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]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文