I got an urgent case from the boss, we had to compare a list of users from our meta-catalog with users in our AD and list and count which users who never logged on to domain. I imported the csv in an variable and then used an foreach-loop to check if the users had logged in or not. We also wanted to list and count all users that where included in the csv-file but not in the active driectory, I used the ErrorVariable to do that and the appended each entry to a text-file with the out-file append switch. As you can see I used two different techniques to export multiple data from the foreach-loop. The first one when I exported the users that hadn´t logged on, where I first created an variable with an empty array “$users = @()” , then instead of running the command to get the users I used the + to fill the array with result “$users +=”, on the second I used the out-file as I explained above. When the lists where done I used the count and length property.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#-------------------------------------------------------------------- #NAME:UsersNeverLogon.ps1 #AUTHOR: Viktor Lindström # #COMMENTS: List and count users accounts that never loged on. #It also lists and counts users that exist in our meta-catalog but #not in our Active directory #-------------------------------------------------------------------- #Import from CSV that contains usesrs samaccountname under header accountname. $import = Import-Csv "C:\temp\acc.txt" #Creates an empty array $users = @() #foreach loop to check all users. foreach ($anv in $import) { #Checks if user dont have the lastLogonTimestamp-attribute set, and if it isn´t set it appends users samaccountname in the array. If the user dosn´t exist in the AD it puts one error code-line in an variable. $users += get-aduser $anv.accountName -ErrorAction SilentlyContinue -ErrorVariable err | Get-ADObject -Properties samaccountname,"lastLogonTimestamp" | where "lastLogonTimestamp" -eq $null | select samaccountname $err | Out-File -FilePath "C:\temp\users_not_in_AD.txt" -Append } #Export users to CSV and counts the users. $users | export-csv -Path c:\temp\users_never_logged_in.txt -NoTypeInformation Write-Host Number of users who have never logged in: $users.count $dontexist = Get-Content C:\temp\users_not_in_AD.txt Write-Host Number of users that are not in active directory $dontexist.Length |