Replace User Accounts in a Group With Computer Accounts

  • 16 September 2016
  • Sean Huggans
Description: 

This script will search through a given Active Directory group and replace any user objects found with a computer object of the same name. This is particularly useful in cases of computer groups used for GPO related settings or machine based deployments, where the group may have accidentally had user accounts added instead of the computer account matching the name. As the script removes user accounts regardless of a matching computer object is found, it leaves you a list of the users without matches so that you have a list of users whose computers you will need to find and add.

Language: 
PowerShell
Usage Type: 
Standalone
Script Source: 
###############################
# ReplaceUserAccountsWithComputerAccounts.ps1
# Script by Sean Huggans
# Original Date: 2016.09.16
###############################
 
import-module ActiveDirectory
 
$ADGroup = "TheBestGroupEver"
$LogDir = "C:\Temp\ReplaceUserAccountsWithComputerAccounts"
 
New-Item -ItemType directory -Path $LogDir -ErrorAction Ignore > $null
echo "There are no computer objects matching the following user objects in $ADGroup.  They have been removed." > "$LogDir\RemovedUsers-$ADGroup.txt"
 
foreach ($Member in $(Get-ADGroupMember -Identity $ADGroup)) {
 if ($Member.objectClass -eq "user") {
 $user = $Member.name
  try {
   $Computer = Get-ADComputer $User
   Add-ADGroupMember $ADGroup $Computer
   Remove-ADGroupMember -identity $ADGroup -members $Member -Confirm:$false
   echo "Matching computer object for user: $User has been added to the group, and the user object has been removed."
  }
  catch {
   Remove-ADGroupMember -identity $ADGroup -members $Member -Confirm:$false
   echo "User - $User has no corresponding computer object and has been removed from the group, added to the removed users log."
   echo $user >> "$LogDir\RemovedUsers-$ADGroup.txt"
  }
 }
}
Note: that all applications posted here are posted for use, both commercial and non-commercial, free of charge, and as such are provided as-is, without warranty of any kind whatsoever. visuaFUSION, FMSCUG or any other program listed here's author are not responsible for any damages or shortcomings that result from usage of any of these applications.
Error | visuaFUSION Systems Solutions Blog

Error message

  • Warning: Cannot modify header information - headers already sent by (output started at /mnt/home/visuafus/public_html/bahusa.net/includes/common.inc:2861) in drupal_send_headers() (line 1551 of /mnt/home/visuafus/public_html/bahusa.net/includes/bootstrap.inc).
  • Error: Call to undefined function mail() in DefaultMailSystem->mail() (line 79 of /mnt/home/visuafus/public_html/bahusa.net/modules/system/system.mail.inc).

Error

The website encountered an unexpected error. Please try again later.