PowerShell Script to Disable AD Accounts After 90 Days

Discover a PowerShell script to disable AD accounts after 90 days. Streamline your account management with this essential guide.
PowerShell Script to Disable AD Accounts After 90 Days

You can use the following PowerShell script to disable Active Directory (AD) accounts that have been inactive for 90 days or more:

Get-ADUser -Filter {(Enabled -eq $true) -and (LastLogonDate -lt (Get-Date).AddDays(-90))} | ForEach-Object {Disable-ADAccount -Identity $_.SamAccountName}

Understanding Active Directory and PowerShell

What is Active Directory?

Active Directory (AD) is a directory service developed by Microsoft for Windows domain networks. It is essential for managing all aspects of the network, including user accounts, computers, and group policies. In enterprise environments, AD serves as a central hub for identity management, allowing administrators to control access to resources and enforce security protocols.

PowerShell Basics

PowerShell is a powerful automation tool and scripting language built on the .NET framework. It provides administrators with the ability to manage tasks through command-line utilities and scripts. Key terminology you should know includes:

  • Cmdlets: Command-line functions within PowerShell.
  • Pipelines: A series of cmdlets connected by the pipe operator (`|`), allowing output from one cmdlet to feed into another.
  • Variables: Containers for storing data, typically prefixed by a dollar sign (`$`).
Powershell Script to Delete User Profiles Older Than 30 Days
Powershell Script to Delete User Profiles Older Than 30 Days

Why Disable Inactive AD Accounts?

Security Implications

Inactive AD accounts can pose a serious security threat. Hackers often exploit these dormant accounts, using them to gain unauthorized access to sensitive information. For instance, a study by the Verizon Data Breach Investigations Report highlights that many breaches involved using compromised accounts that should have been disabled.

Compliance Requirements

Organizations must adhere to various regulatory standards regarding user management, including GDPR and HIPAA. These regulations stress the importance of timely deactivation of accounts that are no longer in use. Disabling inactive accounts not only helps in maintaining security but also assures compliance with industry regulations and best practices.

PowerShell Script Template: Your Quick Start Guide
PowerShell Script Template: Your Quick Start Guide

Getting Started with PowerShell

Setting Up Your Environment

Before you can execute your PowerShell script to disable AD accounts after 90 days, ensure you meet the following requirements:

  • Windows OS: PowerShell comes built-in with modern Windows installations.
  • Active Directory Module: You must have the Active Directory module installed. You can add this feature through the Server Manager in Windows Server or via PowerShell with the command:
    Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools
    

Basic PowerShell Commands

Familiarize yourself with the basic cmdlets that are essential for managing Active Directory. For example:

  • Get-ADUser: Fetch user accounts and their properties.
  • Set-ADUser: Modify properties of AD users.
  • Disable-ADAccount: Disables the specified user account.

These cmdlets serve as your primary tools for managing user accounts within the Active Directory environment.

Mastering the PowerShell UserProfile: A Quick Guide
Mastering the PowerShell UserProfile: A Quick Guide

Crafting the PowerShell Script

Script Overview

The goal of this script is to automate the disabling of AD accounts that have been inactive for 90 days. By doing this, you enhance security and streamline management tasks.

Key Components of the Script

Retrieving User Accounts

To fetch user accounts that haven't logged in for over 90 days, you can use the following code snippet:

$inactiveUsers = Get-ADUser -Filter * -Properties LastLogonDate | Where-Object {
    $_.LastLogonDate -lt (Get-Date).AddDays(-90)
}

Explanation:

  • `Get-ADUser -Filter *` retrieves all AD users.
  • `-Properties LastLogonDate` allows access to the last login timestamp of each account.
  • The `Where-Object` cmdlet filters users based on the condition that their `LastLogonDate` is older than 90 days.

Disabling the User Accounts

Once you've captured these inactive accounts, the next step is to disable them:

foreach ($user in $inactiveUsers) {
    Disable-ADAccount -Identity $user.SamAccountName
}

Explanation:

  • This loop iterates through each user in the `$inactiveUsers` collection.
  • The `Disable-ADAccount` cmdlet disables the specified account based on the `SamAccountName` property.
Harnessing PowerShell OutVariable for Streamlined Scripting
Harnessing PowerShell OutVariable for Streamlined Scripting

Testing and Running the Script

Testing in a Safe Environment

Prior to executing the script in a production environment, it is crucial to test it in a safe and controlled setting. Create a test Organizational Unit (OU) with dummy accounts and verify that the script behaves as expected without causing any disruptions.

Running the Script

You can run your script in various ways:

  • PowerShell ISE: Ideal for writing and debugging.
  • Command Line: Run scripts directly from the command prompt.

You might want to automate this process by scheduling regular runs. Utilize Windows Task Scheduler to execute this script monthly to ensure no account remains inactive for too long.

Mastering PowerShell PSMODULEPATH: A Quick Guide
Mastering PowerShell PSMODULEPATH: A Quick Guide

Logging and Reporting

Good Practices for Documentation

Maintaining logs is vital for auditing purposes. Logging helps you keep track of which accounts were disabled. You can log inactive accounts using:

$inactiveUsers | Export-Csv -Path "InactiveUsersLog.csv" -NoTypeInformation

This command creates a CSV file containing details of all disabled accounts.

Creating Reports

Generating reports is another important aspect of managing AD accounts. A well-structured report should include:

  • A list of disabled accounts and their attributes.
  • Reasons for disabling each account.
  • Recommended actions for account reactivation, if necessary.
Discovering PowerShell Script Location: A Quick Guide
Discovering PowerShell Script Location: A Quick Guide

Troubleshooting Common Issues

Common Errors and Solutions

As with any scripting process, errors may arise. Here are some common issues and their solutions:

  • Access Denied Errors: Ensure that your account has the necessary permissions to disable user accounts in AD.
  • Script Execution Policy Errors: If you encounter script execution policy errors, update your execution policy with:
    Set-ExecutionPolicy RemoteSigned
    

Resources for Further Support

If you run into issues or need guidance, numerous resources are available:

  • Microsoft Documentation: Comprehensive information on PowerShell and AD.
  • Online Forums: Communities like PowerShell.org and Stack Overflow offer valuable user support.
PowerShell Script Generator: Craft Your Scripts Effortlessly
PowerShell Script Generator: Craft Your Scripts Effortlessly

Conclusion

Recap of Key Takeaways

Disabling inactive AD accounts after 90 days is a crucial practice for maintaining a secure and compliant environment. Through automation with PowerShell, you can efficiently manage user accounts, reduce risks, and improve overall system performance.

Encouraging Automation and Continuous Learning

Your journey with PowerShell doesn’t end here. Explore more scripts to automate routine tasks and navigate the vast landscape of PowerShell's capabilities. Continuous learning in this domain will empower you to become a more effective administrator.

How to PowerShell Disable AD User Quickly and Easily
How to PowerShell Disable AD User Quickly and Easily

Additional Resources

Further Reading

To deepen your understanding of PowerShell and Active Directory, consider diving into recommended books and online courses that focus specifically on these topics.

Useful Cmdlets

Familiarizing yourself with various cmdlets related to AD account management will significantly enhance your scripting techniques. A solid command over these tools enables you to automate many tasks efficiently.

By mastering a PowerShell script to disable AD accounts after 90 days, you'll step towards enforcing better security practices and compliance within your organization.

Related posts

featured
2024-07-16T05:00:00

PowerShell Get Disabled Users: A Simple Guide

featured
2024-07-21T05:00:00

PowerShell Script to Install Software Made Easy

featured
2024-01-13T06:00:00

Mastering PowerShell Select-Object in a Nutshell

featured
2024-02-10T06:00:00

Mastering the PowerShell Profiler for Efficient Scripting

featured
2024-02-08T06:00:00

Mastering PowerShell PSCustomObject: A Quick Guide

featured
2024-04-05T05:00:00

PowerShell Hashtable: A Quick Guide to Mastery

featured
2024-06-04T05:00:00

Mastering PowerShell Noprofile for Swift Command Execution

featured
2024-07-06T05:00:00

Mastering PowerShell $Profile for Custom Configurations

Never Miss A Post! 🎉
Sign up for free and be the first to get notified about updates.
  • 01Get membership discounts
  • 02Be the first to know about new guides and scripts
subsc