Perrypackettracer / Powershell-scripts-to-use-in-an-active-directory

0 stars 0 forks source link

5 more usefull powershell scripts #5

Open Perrypackettracer opened 8 months ago

Perrypackettracer commented 8 months ago

Here are five useful PowerShell scripts for managing Active Directory:

  1. User Account Management Script:

    • Objective: Enables tasks such as creating, updating, and disabling user accounts.
    • Script:
      # Sample: Create a new user
      New-ADUser -SamAccountName "JohnDoe" -UserPrincipalName "John.Doe@contoso.com" -GivenName "John" -Surname "Doe" -Enabled $true
  2. Password Expiry Report:

    • Objective: Generates a report of user accounts with approaching or expired passwords.
    • Script:
      $DaysToExpire = 7
      Get-ADUser -Filter {Enabled -eq $true -and PasswordNeverExpires -eq $false} -Properties "SamAccountName", "msDS-UserPasswordExpiryTimeComputed" | 
      Select-Object -Property "SamAccountName",@{Name="PasswordExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}},@{Name="DaysToExpire";Expression={($_."msDS-UserPasswordExpiryTimeComputed" - [datetime]::Now).Days}} | 
      Where-Object { $_.DaysToExpire -le $DaysToExpire -and $_.DaysToExpire -ge 0 } | 
      Sort-Object DaysToExpire | 
      Format-Table -AutoSize
  3. Group Membership Report:

    • Objective: Generates a report of users and their group memberships.
    • Script:
      Get-ADUser -Filter * -Properties MemberOf | ForEach-Object {
       $_ | Select-Object SamAccountName, @{Name="MemberOf";Expression={$_.MemberOf -join ';'}}
      } | Export-Csv -Path "UserGroupMemberships.csv" -NoTypeInformation
  4. Disable Inactive Users:

    • Objective: Disables user accounts that have been inactive for a specified period.
    • Script:
      $InactiveDays = 90
      $InactiveDate = (Get-Date).AddDays(-$InactiveDays)
      Get-ADUser -Filter {LastLogonDate -lt $InactiveDate -and Enabled -eq $true} | Disable-ADAccount
  5. Bulk User Attribute Update:

    • Objective: Updates a specific attribute for multiple users at once.
    • Script:
      # Sample: Set the Department attribute for users in a specific OU
      $OUPath = "OU=Sales,OU=Users,DC=contoso,DC=com"
      $NewDepartment = "Sales"
      Get-ADUser -Filter * -SearchBase $OUPath | ForEach-Object {
       Set-ADUser -Identity $_ -Department $NewDepartment
      }

Before executing any script, ensure that you understand its functionality, customize it based on your environment, and thoroughly test it in a non-production environment to avoid unintended consequences.