Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

With PowerShell how may I record disabled accounts and export the findings to a CSV file?

Posted on 2015-01-28
2
Medium Priority
?
341 Views
Last Modified: 2015-01-29
Hello Expert,

I've cobbled together this script and am unable to output a CSV file with the active accounts and move the inactive accounts to the DisabledAccounts OU. Would you please review this script and offer suggestions to remedy this situation?  Wasn't sure if the issue centered around the 'filter'parameter, 'whatif' parameter or something else.

# Disable inactive user accounts in the domain that have NOT logged in since the specified date
# PowerShell 4.0
# Client OS: Windows 7, Server OS: Windows 2008 R2
# Modified: IT Staff
# Date: 20-Jan-2015

import-module activedirectory
import-module grouppolicy

# Create script variables to apply
# Create a variable for the date stamp in the log file
$LogDate = get-date -f mm-dd-yy

#Sets the OU to do the base search for all user accounts
$SearchBase = "OU=Administrators,OU=Settings,OU=TestOU,OU=AdministratorAccounts,DC=test,DC=local"

#Create an empty array for the log file
$LogArray = @()

#Sets the number of days to disable user accounts based on lastlogontimestamp and pwdlastset.
$PasswordAge = (Get-Date).adddays(-2)

#Use ForEach to loop through all users with pwdlastset and lastlogontimestamp greater than date set. Also add users with no lastlogon date set. Disables the accounts and adds to log array.

#Add the properties you will be using to ensure they are available.
$DisabledUsers = (Get-ADUser -searchbase $SearchBase -Properties samaccountname, name, distinguishedname -Filter {((lastlogondate -notlike "*") -OR (lastlogondate -le $Passwordage) -AND (enabled -eq $True))})

# Code to apply the variables
if ($DisabledUsers -ne $null -and $DisabledUsers.Count > 0) {
    ForEach ($DisabledUsers in $DisabledUsers) {

 #Set the user objects description attribute to a date stamp. Example "19JAN2015" To log only add "-whatif"
      Set-ADuser $DisabledUsers -Description ((get-date).toshortdatestring()) -WhatIf

 #Disabled user object. To log only add "-Whatif"
      Disable-ADaccount $DisabledUsers -WhatIf

 #Create new object for logging
  $obj = New-Object PSObject
  $obj | Add-Member -MemberType NoteProperty -Name "name" -Value $DisabledUsers.name
  $obj | Add-Member -MemberType NoteProperty -Name "samAccountName" -Value $DisabledUsers.samaccountname
  $obj | Add-Member -MemberType NoteProperty -Name "distinguishedname" -Value $DisabledUsers.distinguishedName
  $obj | Add-Member -MemberType NoteProperty -Name "status" -Value 'Disabled User'

 #Adds object to the log array
  $LogArray += $obj

# Move disabled users in TestOU to DisabledAccounts OU
    Search-ADAccount –userAccountControl –UsersOnly –SearchBase “OU=Administrators,OU=Settings,OU=TestOU,OU=AdministratorAccounts,DC=sleepmed,DC=md” | Move-ADObject –TargetPath “OU=DisabledAccounts,OU=TestOU,OU=AdministratorAccounts,DC=test,DC=local”   |
    Move-ADObject –TargetPath “OU=DisabledAccounts,OU=TestOU,OU=AdministratorAccounts,DC=test,DC=local”

#Exports log array to CSV file in the Scripts directory with a date and time stamp.
    $logArray | Export-Csv "C:\Scripts\User_Report.csv" -NoTypeInformation
     
 } else {
            Write-Output "No disabled users to process for $PasswordAge."

        }
}
0
Comment
Question by:CuriousMAUser
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 41

Accepted Solution

by:
footech earned 2000 total points
ID: 40575906
Try the following:
# Disable inactive user accounts in the domain that have NOT logged in since the specified date 
# PowerShell 4.0
# Client OS: Windows 7, Server OS: Windows 2008 R2
# Modified: IT Staff
# Date: 20-Jan-2015 

import-module activedirectory
import-module grouppolicy

# Create script variables to apply
# Create a variable for the date stamp in the log file
$LogDate = get-date -f mm-dd-yy

#Sets the OU to do the base search for all user accounts
$SearchBase = "OU=Administrators,OU=Settings,OU=TestOU,OU=AdministratorAccounts,DC=test,DC=local"

#Create an empty array for the log file
$LogArray = @()

#Sets the number of days to disable user accounts based on lastlogontimestamp and pwdlastset.
$PasswordAge = (Get-Date).adddays(-2)

#Use ForEach to loop through all users with pwdlastset and lastlogontimestamp greater than date set. Also add users with no lastlogon date set. Disables the accounts and adds to log array.

#Add the properties you will be using to ensure they are available.
$DisabledUsers = @(Get-ADUser -searchbase $SearchBase -Properties samaccountname, name, distinguishedname -Filter {((lastlogondate -notlike "*") -OR (lastlogondate -le $Passwordage) -AND (enabled -eq $True))})

# Code to apply the variables
if ($DisabledUsers -ne $null -and $DisabledUsers.Count > 0) {
    ForEach ($DisabledUser in $DisabledUsers) {

    #Set the user objects description attribute to a date stamp. Example "19JAN2015" To log only add "-whatif"
        Set-ADuser $DisabledUser -Description ((get-date).toshortdatestring()) -WhatIf

    #Disabled user object. To log only add "-Whatif"
        Disable-ADaccount $DisabledUser -WhatIf

    #Create new object for logging
        $obj = $DisabledUser | Select Name,samAccountName,distinguishedname,@{n="status";e={'Disabled User'}}

    #Adds object to the log array
        $LogArray += $obj

    # Move disabled users in TestOU to DisabledAccounts OU 
        #Search-ADAccount -AccountDisabled –UsersOnly –SearchBase “OU=Administrators,OU=Settings,OU=TestOU,OU=AdministratorAccounts,DC=sleepmed,DC=md” | Move-ADObject –TargetPath “OU=DisabledAccounts,OU=TestOU,OU=AdministratorAccounts,DC=test,DC=local”   | 
        Move-ADObject $DisabledUser –TargetPath “OU=DisabledAccounts,OU=TestOU,OU=AdministratorAccounts,DC=test,DC=local”

    }
#Exports log array to CSV file in the Scripts directory with a date and time stamp.
    $logArray | Export-Csv "C:\Scripts\User_Report.csv" -NoTypeInformation 
      
    } else {
        Write-Output "No disabled users to process for $PasswordAge."

}

Open in new window


 - Your foreach loop was referencing the same variable twice.
ForEach ($DisabledUsers in $DisabledUsers)
should be
ForEach ($DisabledUser in $DisabledUsers)
and then references after the fact should be adjusted.
 - I put in a more efficient method for creating your new object.
 - The Search-ADAccount command didn't make sense.  There is no -userAccountControl parameter, and there's no need to search for accounts when we already have the object.
 - The closing brackets for the foreach loop and If scriptblock were mixed up.
 - Moved the Export-CSV outside the foreach loop.  If it's inside you have to use the -append switch, otherwise the file will be overwritten each time through the loop.  Since you're collecting all the output in $LogArray, it's better to put this outside the loop.  This is generally also better from a perfomance perspective as you're not repeatedly opening and closing the file which is an expensive operation.
0
 

Author Closing Comment

by:CuriousMAUser
ID: 40577348
Thank you, Footech. Appreciate the correction.
0

Featured Post

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Recently, Microsoft released a best-practice guide for securing Active Directory. It's a whopping 300+ pages long. Those of us tasked with securing our company’s databases and systems would, ideally, have time to devote to learning the ins and outs…
It’s time for spooky stories and consuming way too much sugar, including the many treats we’ve whipped for you in the world of tech. Check it out!
This video Micro Tutorial explains how to clone a hard drive using a commercial software product for Windows systems called Casper from Future Systems Solutions (FSS). Cloning makes an exact, complete copy of one hard disk drive (HDD) onto another d…
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles from a Windows Server 2008 domain controller to a Windows Server 2012 domain controlle…
Suggested Courses

604 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question