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-Objectsyntax:Manageris now a separate property in the selection list, properly separated by commas from the calculatedLastLogonproperty. - Targeted domain controller: The
-Server MYLDC01parameter ensures you're querying the specific local DC you need—critical forLastLogon, since this attribute isn't replicated across domain controllers. - Accurate
LastLogoninstead oflastLogonTimestamp: This aligns with your compliance requirement for 1-day precision, avoiding the 14-19 day replication delay oflastLogonTimestamp. - Handled null
LastLogonvalues: 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
相关产品推荐
相关产品推荐

