[英]Powershell script last logon from ad users last 30 days
Hi everyone can someone help me with the following script.大家好有人可以帮助我使用以下脚本。 the next things must be added:
接下来的事情必须添加:
Much appreciated非常感激
$dcs = Get-ADDomainController -Filter { Name -like "*" }
# create hashtable to keep track of latest timestamps per user
$userLastLogonTable = @{}
foreach($dc in $dcs){
# fetch all users from each DC
Get-ADUser -Filter * -Properties LastLogonDate -Server $dc | ForEach-Object {
# Only add new timestamps to table if we either haven't seen the username before, or if the timestamp is newer than the current
if(-not $userLastLogonTable.Contains($_.SAMAccountName) -or $userLastLogonTable[$_.SAMAccountName].LastLogonDate -lt $_.LastLogonDate){
$userLastLogonTable[$_.SAMAccountName] = [pscustomobject]@{
LastLogonDate = $_.LastLogonDate
LogonServer = $dc.Name
}
}
}
}
# Now that we have a complete table of all users and their last logon timestamp,
# we can then easily identify usernames that have no recent logons
$staleUserNames = $userLastLogonTable.PSBase.Keys |Where-Object { $userLastLogonTable[$_].LastLogonDate -le (Get-Date).AddDays(-30) }
Add the samaccountname value to the custom object:将 samaccountname 值添加到自定义 object:
$userLastLogonTable[$_.SAMAccountName] = [pscustomobject]@{
SAMAccountName = $_.SAMAccountName
LastLogonDate = $_.LastLogonDate
LogonServer = $dc.Name
}
Then filter on the values of the hashtable rather than the keys:然后过滤哈希表的值而不是键:
$staleUserEntries = $userLastLogonTable.PSBase.Values |Where-Object { $_.LastLogonDate -le (Get-Date).AddDays(-30) }
At which point you can export to CSV with Export-Csv
:此时您可以使用
Export-Csv
导出到 CSV:
$staleUserEntries |Select SAMAccountName,LastLogonDate |Export-Csv path\to\output.csv -NoTypeInformation
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.