以下是一个示例代码,可以帮助您设置一个数组,以遍历所有域控制器并进行PowerShell最后登录查询:
# 获取所有域控制器的名称
$domainControllers = Get-ADDomainController -Filter *
# 创建一个空数组来存储查询结果
$lastLogonResults = @()
# 循环遍历每个域控制器
foreach ($dc in $domainControllers) {
# 使用域控制器的名称构建LDAP路径
$ldapPath = "LDAP://$($dc.Name)/"
# 创建一个DirectoryEntry对象以连接到域控制器
$directoryEntry = New-Object System.DirectoryServices.DirectoryEntry($ldapPath)
# 创建一个DirectorySearcher对象以执行查询
$directorySearcher = New-Object System.DirectoryServices.DirectorySearcher($directoryEntry)
# 设置查询过滤器以获取所有用户,并指定返回的属性
$directorySearcher.Filter = "(&(objectCategory=User)(objectClass=User))"
# 指定要返回的属性
$directorySearcher.PropertiesToLoad.AddRange(@("sAMAccountName", "lastLogonTimestamp"))
# 执行查询
$searchResults = $directorySearcher.FindAll()
# 循环遍历查询结果
foreach ($result in $searchResults) {
# 获取用户名和最后登录时间戳
$username = $result.Properties["sAMAccountName"][0]
$lastLogonTimestamp = [System.DateTime]::FromFileTime([Int64]::Parse($result.Properties["lastLogonTimestamp"][0]))
# 创建一个自定义对象,将用户名和最后登录时间戳添加到数组中
$lastLogonResult = [PSCustomObject]@{
Username = $username
LastLogonTimestamp = $lastLogonTimestamp
}
$lastLogonResults += $lastLogonResult
}
}
# 按最后登录时间戳降序排序结果
$lastLogonResults = $lastLogonResults | Sort-Object -Property LastLogonTimestamp -Descending
# 打印最后登录查询结果
$lastLogonResults | Format-Table -AutoSize
这段代码首先使用Get-ADDomainController cmdlet获取所有域控制器的名称,并存储在$domainControllers变量中。然后,它通过循环遍历每个域控制器,使用System.DirectoryServices.DirectorySearcher对象执行PowerShell最后登录查询。查询结果存储在$lastLogonResults数组中,并按最后登录时间戳降序排序。最后,使用Format-Table cmdlet打印最后登录查询结果。
请注意,此代码需要在安装了Active Directory模块的计算机上运行,并使用具有适当权限的用户执行。
上一篇:帮助设置使用时钟源的数字输出的ATSAMD51G19
下一篇:帮助识别用户输入