Trying to get AD users and disable them in one script

Daniel Yarmishin 21 Reputation points
2022-03-14T08:52:18.15+00:00

Hey (:
I'm new to AD and powershall. I need to get a list (csv) of users who didn't connect X days and then disable their accounts.
For some reason I cant get past it, I made one script that gets the list, another that disables them. On separate they seem to work but when I combine them they wont work.
here are the scripts :

182738-image-6483441.jpg182791-image-6483441-1.jpg

Windows for business | Windows Client for IT Pros | Directory services | Active Directory
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Thameur-BOURBITA 36,261 Reputation points Moderator
    2022-03-14T10:27:46.307+00:00

    Hi,

    You can use the second script provided in my previous answer or just add a line to export user before the disable like this:

        $Date = (Get-Date).AddDays(-90)
    
       Get-ADUser -Filter {LastLogonDate -le $Date  }  -Properties LastLogonDate| select Samaccountname,LastLogonDate | Export-csv c:\lastlogon.csv
        Get-ADUser -Filter {LastLogonDate -le $Date  }  -Properties LastLogonDate,lastLogonTimestamp  | Disable-ADAccount
    

    Please don't forget to mark helpful reply as answer

    2 people found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Thameur-BOURBITA 36,261 Reputation points Moderator
    2022-03-14T09:59:35.457+00:00

    Hi,

    You can use one command instead of your method:

    $Date = (Get-Date).AddDays(-90)
    Get-ADUser -Filter {LastLogonDate -le $Date  }  -Properties LastLogonDate,lastLogonTimestamp  | Disable-ADAccount
    

    You can also use another this script if you want generate a log file to track all modification performed by the script:

    $Date = (Get-Date).AddDays(-90)
    
    $logfile = "c:\temp\logfile.log"
    
    $Userlist = Get-ADUser -Filter {LastLogonDate -le $Date  }  -Properties LastLogonDate,lastLogonTimestamp | select -ExpandProperty SamaAccountname
    
    foreach($UserName in $Userlist)
    
    {
    try{
    
    get-aduser -identity $userName -ErrorAction Stop | Disable-ADAccount -ErrorAction Stop
    
    add-content -value "$username disabled" -Path $logfile
    }
    
    catch{
    
    add-content -value "Error to disable $username : $_" -Path $logfile
    
    
    }
    
    
    }
    

    Please don't forget to mark helpful reply as answer

    2 people found this answer helpful.

  2. Anonymous
    2022-03-14T09:39:36.013+00:00

    Hi,

    Please post your code using the Code Sample button or the Ctrl+K shortcut.

    Do you see any error messages if you run both scripts?

    Best Regards,
    Ian Xue


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.