Friday, December 26, 2014

Adding workstations to an account's allowed workstation list

For anyone that uses the Logon Workstations attribute on user accounts to restrict what machines an account logs on to, you may find that updating the list can be a bit tedious from the GUI. Updating it from command line tools isn't always easy as well. The attribute in AD is just a string value, and all of the "list" that comes from it is due to the fact that it is stored in CSV format. So you have a list with a max length of 1024 characters in this format, so adding machines to it requires that it be added to the existing list, formatted as csv and limited in length. I put together a script for managing this, though it was targeted at accounts that already have some entries in this attribute, so it may require some extra work to target accounts that don't have any values. This script will check the length and content of each entry to ensure they meet netbios name standards. It will also ignore any duplicates that you may have provided.

param (
Try {
 if ($workstation -is [array]) {
   $workstation = $workstation -join ","
 $UserAccount = Get-ADUser $targetaccount -properties logonworkstations
 if ($useraccount -eq $null) {
  Write-Host "We have NOT found the account $targetaccount"
  throw "Target account not found"
 $UsrAcctArray = $UserAccount.logonworkstations.split(",")
 #clear out any whitespace in the user input
 if ($workstation.length -gt 15 -and $workstation -notmatch ",") {
  throw "Workstations provided are not correct.  Computer names can only be 15 characters or less."

#check all provided names to ensure they meet MS netbios name standards for machines.  If they don't ignore the name provided
 foreach($entry in $Workstation.split(",")){
  $entry = $entry.trim()
  if ((([regex]::match($entry,'^[0-9a-zA-Z_-]{5,15}$')).success) -eq $true) {
   $WorkstationCDL = $WorkstationCDL + $entry.ToUpper() + ","
 #if we have received no valid machines, quit
 if ([string]::isnullorempty($workstationCDL)) {
  throw "No Valid workstation names provided.  Please provide a name that meet Microsoft standards."
 #remove trailing comma, change new workstations to an array, mash it with the old one and check the length.  
 $WorkstationCDL = $WorkstationCDL.substring(0,($WorkstationCDL.length -1))      
 $WKSTarray = $WorkStationCDL.split(",")
 #mash arrays and pull unique names
 $newWorkstations = (($UsrAcctArray + $WKSTarray |select-object -Unique) -join ",").toupper()
 #check length (attribute max is 1024 chars
 if ($newworkstations.length -gt 1024) { 
  throw "The account has too many computers.  Cannot add more."
 try {
  Set-ADUser -identity $targetaccount -logonworkstations $newworkstations
 } catch {
  throw "Unable to modify user object."
} catch { throw $_ }

No comments:

Post a Comment