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

PowerShell获取AD用户LastLogonDate计算登录间隔天数报错问题

错误产生原因

这个Cannot find an overload for "op_Subtraction" and the argument count: "2"报错的核心原因是$CurrentDate - $Result.LastLogonDate这个减法运算不合法,触发场景分为两种:

  • $Result.LastLogonDate为$null:如果查询的AD用户从来没有过登录记录,LastLogonDate属性会是空值,无法和DateTime类型的当前日期做减法运算
  • 变量残留污染:你的脚本没有提前初始化$Message变量,PowerShell会话中如果之前运行过报错的查询,$Message会留存之前的报错值,哪怕本次查询完全正常,最终输出的JSON里也会携带旧的错误信息,这也是你现在看到「结果正确但同时有报错」的最常见原因

解决方法

按以下步骤修改脚本即可:

  1. 脚本开头初始化所有用到的变量,避免会话残留值干扰
  2. 运算前先校验LastLogonDate是否为空、是否为合法DateTime类型
  3. 对空值场景做兼容处理,避免无意义的报错

修改后的参考脚本如下:

# 初始化变量,避免会话残留
$User = $null
$Message = $null
$Result = Get-ADUser -filter {SamAccountName -eq 'username'} -Properties UserPrincipalName, mail, LastLogonDate, Enabled
$CurrentDate = Get-Date
Write-Host $Result.LastLogonDate

try
{
    # 先校验LastLogonDate是否合法
    if ($null -ne $Result.LastLogonDate -and $Result.LastLogonDate -is [DateTime]) {
        $LastLogonDays = ($CurrentDate - $Result.LastLogonDate).Days
    } else {
        # 无登录记录的场景自定义值,比如设为-1或者提示无记录
        $LastLogonDays = -1
    }
    Write-Host $LastLogonDays
    $Json = @{
        "UserPrincipalName"= $Result.UserPrincipalName;
        "mail"= $Result.mail;
        "LastLogonDate"= $Result.LastLogonDate?.ToString() ?? "无登录记录";
        "days"= $LastLogonDays
    }
    $User = $Json
}
catch{
    $Message = $_.Exception.Message
}

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:57:03