I am beginner in scripting with powershell. My boss asked me to create a script that will get information about the last logon from every user in our domain on every DC. I have created the following script:
Import-Module ActiveDirectory
function Get-ADUsersLastLogon() {
$dcs = Get-ADDomainController -Filter { Name -like "*" }
$users = Get-ADUser -Filter * -Properties LastLogonDate | Where-Object { $_.LastLogonDate -le (Get-Date).AddDays(-30) }
$time = 0
$exportFilePath = "C:\output\aduser.csv"
$columns = "name,username,datetime,domain controller,enabled"
Out-File -filepath $exportFilePath -force -InputObject $columns
foreach ($user in $users) {
$Activeuser = $user.Enabled
foreach ($dc in $dcs) {
$hostname = $dc.HostName
$currentUser = Get-ADUser $user.SamAccountName | Get-ADObject -Server $hostname -Properties lastLogon
if ($currentUser.LastLogon -gt $time) {
$time = $currentUser.LastLogon
}
}
$dt = [DateTime]::FromFileTime($time)
$row = $user.Name + "," + $user.SamAccountName + "," + $dt + "," + $hostname + "," + $Activeuser
Out-File -filepath $exportFilePath -append -noclobber -InputObject $row
$time = 0
}
}
Get-ADUsersLastLogon
My boss asked me to change the following things in this script:
- the output of the domain controller is only our DC in an other country. I want to know which DC the user last logged into.
- The running of the script is taking too long. Like half a day. Is it possible to make this faster?
I hope someone can help me with this, I tried a few things, but I didn't work :(