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

PowerShell操作ActiveDirectory:获取指定OU内启用用户的可读LastLogon信息、Manager并限定本地域控制器的实现及报错解决

PowerShell AD User Script: Fix Syntax Error & Retrieve Accurate LastLogon + Manager Info

Let's break down what went wrong and fix your script to fully meet all your requirements:

The Root Cause of Your Syntax Error

Your modified script has a simple syntax mistake in the Select clause: you tried to include Manager inside the custom property hashtable for LastLogon instead of listing it as a separate, standalone property. Calculated property hashtables need to be individual items in the Select list, separated by commas from other properties.

Fixed Script That Meets All Your Requirements

Here's the corrected code that addresses every part of your request:

Get-ADUser -Filter {enabled -eq $true} `
    -Server MYLDC01 `
    -SearchBase "OU=STAFF,OU=MINE,DC=mine,DC=local" `
    -ResultPageSize 0 `
    -Properties CN, LastLogon, Manager |
Select-Object CN,
    @{Name = "LastLogon"; Expression = {
        # Handle cases where LastLogon is null (user never logged on)
        if ($_.LastLogon) {
            [datetime]::FromFileTime($_.LastLogon)
        } else {
            "Never logged on"
        }
    }},
    Manager |
Export-Csv -NoTypeInformation -Path "c:\temp\lastLogon.csv"

Key Changes & Explanations

  • Fixed Select-Object syntax: Manager is now a separate property in the selection list, properly separated by commas from the calculated LastLogon property.
  • Targeted domain controller: The -Server MYLDC01 parameter ensures you're querying the specific local DC you need—critical for LastLogon, since this attribute isn't replicated across domain controllers.
  • Accurate LastLogon instead of lastLogonTimestamp: This aligns with your compliance requirement for 1-day precision, avoiding the 14-19 day replication delay of lastLogonTimestamp.
  • Handled null LastLogon values: Added a check to avoid errors if a user has never logged on, returning a human-readable message instead of a broken timestamp.
  • Clean formatting: Used backticks (`) to split the command into multiple lines for readability (optional but helpful for long scripts).

Optional Enhancement: Get Manager's Name Instead of DN

If you want the manager's friendly name instead of their distinguished name, replace the plain Manager in the Select-Object list with this calculated property:

@{Name = "ManagerName"; Expression = {
    if ($_.Manager) {
        (Get-ADUser $_.Manager).Name
    } else {
        "No manager assigned"
    }
}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 15:22:41