来自所有域控制器CSV输出的Lastlogon [英] Lastlogon from All Domain Controllers CSV output
问题描述
我遇到了以下脚本,这些脚本几乎可以满足我的要求.它查询所有域控制器,并获取最近登录的时间和日期.
我正在尝试针对AD运行它,即使用"-Searchbase"
参数get我希望能够以包含samaaccountnme,Searchbase位置和lastlogon时间的csv格式获取结果.
I came across the following script that almost meets my requirement. It queries all the domain controllers and gets the recent logged in time and date.
What i am trying to do is run it against AD i.e. using "-Searchbase"
parameter get i want to be able to get the results in a csv format containing samaaccountnme, Searchbase location and lastlogon time.
出于审计目的,这是必要的.
It is essentail for the auditing purposes.
Import-Module ActiveDirectory
function Get-ADUserLastLogon([string]$userName)
{
$dcs = Get-ADDomainController -Filter {Name -like "*"}
$time = 0
foreach($dc in $dcs)
{
$hostname = $dc.HostName
$user = Get-ADUser $userName | Get-ADObject -Server $hostname -Properties lastLogon
if($user.LastLogon -gt $time)
{
$time = $user.LastLogon
}
}
$dt = [DateTime]::FromFileTime($time)
Write-Host $username "last logged on at:" $dt }
Get-ADUserLastLogon -UserName testuser
我什至尝试更改以下行,我认为这行可以解决,但没有运气.
I even tried changing the following line that i thought would fixes it but no luck.
$user = Get-ADUser -Filter * -Properties * -Searchbase "OU=Staff,DC=Home,DC=ac,DC=uk" | Get-ADObject -Server $hostname -Properties lastLogon
Get-AduserLastLogon $Username
有人可以帮忙吗?
推荐答案
以下是如何获取所有DC上用户的最新lastLogon属性的示例:
Here is an example of how to get most recent lastLogon attribute for users on all DCs:
# Get a list of every domain controller's name
$dcNames = Get-ADDomainController -Filter * |
Select-Object -ExpandProperty Name |
Sort-Object
# Get a collection of users in specified OU
$searchBase = "OU=Sales,DC=fabrikam,DC=com"
$users = Get-ADUser -Filter * -SearchBase $searchBase
# Hashtable used for splatting for Get-ADUser in loop
$params = @{
"Properties" = "lastLogon"
}
foreach ( $user in $users ) {
# Set LDAPFilter to find specific user
$params.LDAPFilter = "(sAMAccountName=$($user.SamAccountName))"
# Clear variables
$latestLogonFT = $latestLogonServer = $latestLogon = $null
# Iterate every DC name
foreach ( $dcName in $dcNames ) {
# Query specific DC
$params.Server = $dcName
# Get lastLogon attribute (a file time)
$lastLogonFT = Get-ADUser @params |
Select-Object -ExpandProperty lastLogon
# Remember most recent file time and DC name
if ( $lastLogonFT -and ($lastLogonFT -gt $latestLogonFT) ) {
$latestLogonFT = $lastLogonFT
$latestLogonServer = $dcName
}
}
if ( $latestLogonFT -and ($latestLogonFT -gt 0) ) {
# If user ever logged on, get DateTime from file time
$latestLogon = [DateTime]::FromFileTime($latestLogonFT)
}
else {
# User never logged on
$latestLogon = $latestLogonServer = $null
}
# Output user
$user | Select-Object `
SamAccountName,
@{Name = "LatestLogon"; Expression = {$latestLogon}},
@{Name = "LatestLogonServer"; Expression = {$latestLogonServer}}
}
这篇关于来自所有域控制器CSV输出的Lastlogon的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!