You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中使用Get-LastLogon比较日期失败问题求助

问题排查与解决

核心原因:日期类型不匹配

你的$LogonDate大概率是字符串类型,而$cutoffDate是PowerShell的DateTime对象,直接用-lt比较字符串和DateTime对象会导致逻辑错误:PowerShell会把DateTime对象转换成字符串后按字典序对比,而非实际的时间先后。

从你给出的变量值来看,$LogonDate(2023-12-11)明明早于$cutoffDate(2024-06-07),但脚本没输出"ok",就是类型不匹配导致的。

验证方法

先执行以下命令确认两个变量的类型:

$LogonDate.GetType().Name
$cutoffDate.GetType().Name

如果$LogonDate返回的是String,$cutoffDate返回DateTime,就坐实了类型问题。

修复方案

把$LogonDate强制转换为DateTime对象后再比较,修改脚本如下:

# Define the date 90 days ago from today
$cutoffDate = (Get-Date).AddDays(-90)

# 将返回的字符串日期转换为DateTime对象
$LogonDate = [DateTime](Get-LastLogon -Identity "user").DateTime
# 或者用Get-Date转换:$LogonDate = Get-Date (Get-LastLogon -Identity "user").DateTime

if ($LogonDate -lt $cutoffDate) {
    #Do something
    write-host "ok"
}

额外注意点

  • 如果Get-LastLogon返回的日期格式和系统区域设置不兼容,强制转换可能失败,这时可以指定格式转换:
    $LogonDate = [DateTime]::ParseExact((Get-LastLogon -Identity "user").DateTime, "dddd, MMMM d, yyyy h:mm:ss tt", $null)
    
    格式字符串要和你的$LogonDate输出格式完全匹配。

内容的提问来源于stack exchange,提问作者Arbelac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 19:57:13