问题
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
Can someone please help please.
回答1:
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}}
}
来源:https://stackoverflow.com/questions/41042336/lastlogon-from-all-domain-controllers-csv-output