PowerShell – export AD user account info to csv
This script can be used for exporting user account onformation fra Active Directory…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
cls $outfile = 'c:\temp\serviceaccounts-' + (Get-Date -Format yyyy-MM-dd_hh-mm-ss) + '.txt' "sAMAccountName" + ";" + "SN" + ";" + "Initials" + ";" + "displayName" + ";" + "department" + ";" + "Land" + ";" + "description" + ";" + "manager" + ";" + "physicalDeliveryOfficeName" + ";" + "userPrincipalName" + ";" + "mail" + ";" + "Lastlogon" + ";" + "AccountExpires" + ";" + "enabled" | Out-File -FilePath $outfile -Append -Force $userarray = Get-ADUser -SearchBase “dc=somedomain,dc=local” -Filter * -Properties * | ? { ($_.distinguishedname -notlike '*Employees*') } $userarray.count foreach ($user in $userarray) { if (!$user.Lastlogontimestamp) { $StrLastlogonTimeStamp = "Never" } else { $StrLastlogonTimeStamp = Get-Date ([datetime]::fromfiletime($user.Lastlogontimestamp)) -Format "yyyy-MM-dd hh:mm:ss" $StrLastlogon = (Get-Date ([datetime]::fromfiletime($user.Lastlogon)) -Format "yyyy-MM-dd hh:mm:ss") #if ($StrLastlogonTimeStamp -ne $StrLastlogon) {write-host ($StrLastlogonTimeStamp);write-host ($StrLastlogon)} } if (($user.AccountExpires -eq 9223372036854775807) -or ($user.AccountExpires -eq 0)) { $StrAccountExpires = "Never" } else { $StrAccountExpires = Get-Date ([datetime]::fromfiletime($user.AccountExpires)) -Format "yyyy-MM-dd hh:mm:ss" } $string = "$($user.SamAccountName);$($user.SN);$($user.Initials);$($user.displayName);$($user.Department);$($user.Land);$($user.description);$($user.manager);$($user.physicalDeliveryOfficeName);$($user.userPrincipalName);$($user.mail);$StrLastlogonTimeStamp;$StrAccountExpires;$($user.enabled)" $string | Out-File -FilePath $outfile -Append -Force } |