Updating User Workstations through PowerShell

Below is a simple PowerShell script that can be used to search for all currently restricted accounts in Active Directory (accounts who have a value for userWorkstations), and update their list of workstations by adding/removing hosts as needed.

This script might be most useful in a scenario where you are upgrading your environment, and replacing servers with new ones that have different names, such as your webmail servers or file servers.

# LDAP Filter, searches for all accounts with workstations
$strFilter = '(&(objectCategory=User)(userWorkstations=*))'

# Workstations to add to restrictions
$addStations = [string[]]( "workstation123", "webmail" )

# Workstations to remove from restrictions
$removeStations = [string[]]( "workstation234", "test2", "IDONOTEXIST" )

# LDAP Search String (edit as needed!)
$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://OU=Standard Users,OU=ORGUNIT,DC=domain,DC=com")

# Create the Searcher
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"

# Properties to load
$colPropList = [string[]]( "samaccountname", "userworkstations" )

# Load Properties
foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) }

# Get Results
$colResults = $objSearcher.FindAll()

# Loop through accounts
foreach ($objResult in $colResults) {  
 $User = $objResult.GetDirectoryEntry();
 $samAccountName = $User.samAccountName;
 $userWorkstations = [string]$User.userWorkstations;
 # Convert workstations to an array
 $userWorkstationsArray = $userWorkstations.split(",")

 # Add workstations if they don’t already exists
 foreach ($temp in $addStations) {
  # Add only if it doesn't already exist
  if (!($userWorkstationsArray -contains $temp)) {
   $userWorkstationsArray += $temp;
  }
 }

 # Remove workstations if they exist
 foreach ($temp in $removeStations) {
  $userWorkstationsArray = $userWorkstationsArray |? { $_ -ne $temp }
 }

 # Make sure you only have unique entries (removes duplicates!)
 $userWorkstationsArray = $userWorkstationsArray | select –uniq

 # Convert to a comma separated string
 $newWorkstations = $userWorkstationsArray -join ","

 # Debugging output
 Write-Host "$samAccountName : '$userWorkstations'"
 Write-Host $newWorkstations

 # ######################
 # UNCOMMENT BELOW IF YOU WANT TO SAVE THE CHANGES
 # ######################
 #$User.userWorkstations = $newWorkstations; # Updates the userWorkstations property
 #$User.SetInfo(); # Saves the record
}