【问题标题】:Handling Date in Power-Shell JSON Object处理 Power-Shell JSON 对象中的日期
【发布时间】:2021-10-19 06:25:11
【问题描述】:

我正在尝试根据来自 AD 的 LastLogondate 获取用户信息。我正在将最终输出转换为 JSON 格式。

这里是处理日期的小脚本。实际上,我将 $PasswordAge 作为用户的 LastLogonDate 传递。

 $PasswordAge = (Get-Date).AddDays(-60) # This is actually LastLogonDate from user info
$CurrentDate = (Get-Date)
#Write-Host $PasswordAge
try
{
$LastLogonDays = (New-TimeSpan -Start $PasswordAge -End $CurrentDate).Days
#Write-Host $LastLogonDays
}
catch{
$Message = $_.Exception.Message
}

$JSONOutput = @{"result"=$LastLogonDays;"error"=$Message} | ConvertTo-Json #-Compress
Write-Output $JSONOutput 

如果我使用 ConvertTo-Json 并打印输出,则会收到以下错误。日差是正确的,但每次都收到错误消息

 {
    "error":  "Cannot bind parameter \u0027Start\u0027 to the target. Exception setting \"Start\": \"Cannot convert null to type \"System.DateTime\".\"",
    "result":  60
} 

提前感谢您的帮助。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    New-TimeSpan 糟透了。我几乎总是遇到同样的错误。据报道,该问题源于操作系统上的文化(语言)设置不匹配、操作系统配置为用于日期和时间的格式以及DateTime 对象的实际格式不匹配。我住在美国,使用英语,并使用我们的标准日期格式,但我仍然无法让New-TimeSpan 正常工作。我早就放弃了让这个 cmdlet 始终如一地工作。

    幸运的是,有一个简单的解决方法;只需减去两个日期时间即可获得System.TimeSpan。每次都有效。

    $LastLogonDays = ( $CurrentDate - $PasswordAge ).Days
    

    【讨论】:

    • 感谢您的快速回复。我实际上是在尝试根据“LastlogonDate”找出用户上次登录以来的天数,但在将最终输出转换为 JSON 时出现错误。我尝试了 '''[DateTime]::Now''' 但仍然没有运气
    • @snowcoder 您在ConvertTo-Json 上没有收到错误消息。您在New-TimeSpan 中收到错误消息。我的-Start-End 参数经常发生这种情况,除了不使用它之外,我从来没有找到合适的解决方案。从$CurrentDate 中减去$PasswordAge 得到您正在寻找的TimeSpan
    • 对混淆道歉,我已经用我实际想要实现的内容更新了原始帖子。看起来很简单的“-”正在按照您的建议工作,但仍然捕获了新错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 2011-03-21
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    相关资源
    最近更新 更多