Noam's scripting blog

"Ready to use" scripts and scripting tips for system admins with detailed walkthroughs/explanations.

Sidebar

Recent Posts

  • Powershell – Split PFX certificates April 3, 2017
  • Remove a VMFS datastore using powershell August 13, 2014
  • Get windows time settings from remote servers July 31, 2014
  • Logoff RDP sessions on multiple servers July 22, 2014
  • Synchronize folder/directory contents June 10, 2014
Follow Noam's scripting blog on WordPress.com
  • Home
  • About Me

ActiveDirectory

Powershell – Find unused AD computer accounts and export to CSV

Standard

This script will help you find unused computer accounts and help you keep your active directory free of obsolete objects. The script scans the active directory and finds all computer accounts which haven’t “logged on” or authenticated to a DC for a given number of days. The results are then exported to CSV.
Even though the script is very short and simple I have split it into three parts variables, functions and script main for added clarity.

Variables

#VARIABLES
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath #path to the directory in which the script is run.
$CSV =  "$dir\$(get-date -format "yyyy-MM-dd HH-mm-ss")_UnusedComputerAccounts.csv" #results will be exported to csv to a file with this path
#Parameters
$DaysBack = 90 #computer accounts who haven't authenticated in this amount of days will be exported to CSV.

$CSV is the path to the CSV file which will be created and the end of the script run. It relies on the object $dir which always points to the directory which the script was started in. This is practical as it allows me to copy and move the script around without having to change any paths.
Remember to set the $DaysBack value to your needs before you run the script.

Functions

#FUNCTIONS
function Find-UnusedComputers {
	if (-not(Get-Module -name "activedirectory")) {    
	Import-Module ActiveDirectory | out-null
	}	
	$unusedComputers = @(get-adcomputer -properties lastLogonDate -filter * | where { $_.lastLogonDate -lt (get-date).addDays(-$DaysBack)})
	$unusedComputers = $unusedComputers | Sort-Object @{Expression={$_.LastLogonDate}}
	Return $unusedComputers
}

1. Function Find-UnusedComputers
The script only has this single function. First it imports active directory module for powershell and then uses the cmdlet Get-ADComputer to get all the computer accounts that haven’t authenticated in $DaysBack days. The results are then sorted by last logon date using Sort-Object and the @{Expression} syntax which allows me to sort by the properties of the array elements. The unused computers are then returned.

Script Main

#SCRIPT MAIN
$unusedComputers = Find-UnusedComputers 
$unusedComputers | Export-CSV $CSV -force -NoTypeInformation 

The script main is very simple consisting of only two lines. First I use the Find-UnusedComputers function to get the computer accounts. Then, in the second line, the results are exported to CSV.

I have copied in the full script below. I hope you find it useful.

 #####################################################################################
##Script:		Get-UnusedComputers.ps1
##Description:	Finds unused computer accounts in the AD by getting all computer
#+				accounts with a last logon date older than $daysback days. The results
#+				are then exported to a CSV file.
##Created by:	Noam Wajnman
##Created:		December 25, 2012
##Updated:		April 07, 2014
#####################################################################################
#FUNCTIONS
function Find-UnusedComputers {
	if (-not(Get-Module -name "activedirectory")) {    
	Import-Module ActiveDirectory | out-null
	}	
	$unusedComputers = @(get-adcomputer -properties lastLogonDate -filter * | where { $_.lastLogonDate -lt (get-date).addDays(-$DaysBack)})
	$unusedComputers = $unusedComputers | Sort-Object @{Expression={$_.LastLogonDate}}
	Return $unusedComputers
}
#VARIABLES
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath #path to the directory in which the script is run.
$CSV =  "$dir\$(get-date -format "yyyy-MM-dd HH-mm-ss")_UnusedComputerAccounts.csv" #results will be exported to csv to a file with this path
#Parameters
$DaysBack = 90 #computer accounts who haven't authenticated in this amount of days will be exported to CSV.
#SCRIPT MAIN
$unusedComputers = Find-UnusedComputers 
$unusedComputers | Export-CSV $CSV -force -NoTypeInformation
Advertisement

Share this:

  • Facebook
  • Twitter
  • Print
  • Email

Like this:

Like Loading...
  • Date April 8, 2014
  • Tags active directory, ActiveDirectory, computer account, computer accounts, CSV file, get-adcomputer, obsolete computer accounts, powershell, script, unused, unused computer accounts
  • Comments Leave a comment

Powershell – Get obsolete active directory users and export results to CSV

Standard

When maintaining and cleaning up your active directory it can be useful to know if any user accounts have become obsolete. Account of users who have left the company and old application accounts may still exist in your active directory causing a mess and/or potential gaps in your security. With this script you can scan the active directory for user accounts who haven’t authenticated or logged in for a given number of days. The results will be exported to a CSV file which will allow you to review the results and take any appropriate actions.
I have divided the script into two sections “variables” and “script main” which I will go over below.

Variables

#VARIABLES
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath #$dir is the path to the directory which the script is being run from
$outputFile =  "$dir\$(get-date -format "yyyy-MM-dd HH-mm-ss")_ObsoleteUsers.csv"
#parameters
$DaysBack = 30 #Gets users who haven't logged in for this number of days

$outputFile is the path of the CSV file which will be created each time you run the script. It includes a time stamp for future reference and to avoid overwriting.
Before running the script you need to set the $DaysBack parameter to the desired number of days.

Script Main

#SCRIPT MAIN
if (-not(Get-Module -name "activedirectory")) {    
Import-Module ActiveDirectory | out-null
}
$Date = (Get-Date).addDays(-$DaysBack)
$Users = @() #Create blank array to hold users who haven't logged in for $DaysBack days		 
	Get-ADUser -filter {(LastLogon -le $Date) -and (Name -like "*")} -Properties Lastlogon,whenCreated | % {			
	$LastLogon = $_.LastLogon
	$LastLogon_DT = [datetime]::FromFileTime("$LastLogon") #convert logon time to a datetime object
	$User = "" | select Name,LastLogon,FullName,WhenCreated #creating a custom object
	$User.Name = $_.SamAccountName 
	$User.LastLogon = $LastLogon_DT
	$User.FullName = $_.Name
	$User.WhenCreated = $_.WhenCreated
	$Users += @($User) #Add user to $Users array		
}
$ObsoleteUsers = $Users | sort-object Lastlogon #sorting results by last logon time
$ObsoleteUsers | Export-CSV $outputFile -force -NoTypeInformation #Export results to CSV in script directory

The first thing to happen is that the active directory module for powershell is imported (if not already imported). I then create the blank array $users to hold results of the coming AD search. The cmdlet Get-ADUser is then used to get the users who haven’t authenticated/logged on for $DaysBack days. For each user found, a custom object with the properties “name”, “lastlogon”, “fullname” and “whencreated” is created and added to the $users array. The results are then sorted by last logon time and then exported to a CSV file.
I have copied in the full script below. I hope you find this script useful!

##################################################################################################################
##Script:			Get-ObsoleteUsers.ps1
##Description: 		Gets users in the active directory who haven't logged in for a given number of days (specified
#+					in the parameter $DaysBack) and then exports the results to CSV.
##Created by: 		Noam Wajnman
##Creation Date: 	March 5, 2013
##Updated:			March 31, 2014
###################################################################################################################
#VARIABLES
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
$outputFile =  "$dir\$(get-date -format "yyyy-MM-dd HH-mm-ss")_ObsoleteUsers.csv"
#parameters
$DaysBack = 30 #Gets users who haven't logged in for this number of days
#SCRIPT MAIN
if (-not(Get-Module -name "activedirectory")) {    
Import-Module ActiveDirectory | out-null
}
$Date = (Get-Date).addDays(-$DaysBack)
$Users = @() #Create blank array to hold users who haven't logged in for $DaysBack days		 
	Get-ADUser -filter {(LastLogon -le $Date) -and (Name -like "*")} -Properties Lastlogon,whenCreated | % {			
	$LastLogon = $_.LastLogon
	$LastLogon_DT = [datetime]::FromFileTime("$LastLogon") #convert logon time to a datetime object
	$User = "" | select Name,LastLogon,FullName,WhenCreated #creating a custom object
	$User.Name = $_.SamAccountName 
	$User.LastLogon = $LastLogon_DT
	$User.FullName = $_.Name
	$User.WhenCreated = $_.WhenCreated
	$Users += @($User) #Add user to $Users array		
}
$ObsoleteUsers = $Users | sort-object Lastlogon #sorting results by last logon time
$ObsoleteUsers | Export-CSV $outputFile -force -NoTypeInformation #Export results to CSV in script directory

Share this:

  • Facebook
  • Twitter
  • Print
  • Email

Like this:

Like Loading...
  • Date March 31, 2014
  • Tags accounts, active directory, ActiveDirectory, AD, csv, CSV file, last login, last logon, lastlogon, logon date, obsolete users, powershell, script, user accounts, users
  • Comments 2 Comments
Blog at WordPress.com.
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
  • Follow Following
    • Noam's scripting blog
    • Join 39 other followers
    • Already have a WordPress.com account? Log in now.
    • Noam's scripting blog
    • Customize
    • Follow Following
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
%d bloggers like this: