Skip to content

Instantly share code, notes, and snippets.

@AfroThundr3007730
Last active March 14, 2021 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AfroThundr3007730/ad8ff04e01a205ff19c51be944c58467 to your computer and use it in GitHub Desktop.
Save AfroThundr3007730/ad8ff04e01a205ff19c51be944c58467 to your computer and use it in GitHub Desktop.
Script to set msDS-PrimaryComputer attribute by OU mapping
# Script to enforce Primary Computer attribute by OU mapping
# Used to limit the scope of roaming profiles and folder redirection
Start-Transcript 'C:\ProgramData\primary-computers.log' -Append
Write-Host 'Checking and updating user Primary Computer mappings.'
# Define group mapping array
$groupMappings = @()
# Add members to array
$groupMappings += @{
userOU = '<OU containing users to modify>'
machineOU = '<OU containing machines to add>'
}
# $groupMappings += @{
# userOU = '<additional user OUs>'
# machineOU = '<additional machine OUs>'
# }
$pcAttrib = 'msDS-PrimaryComputer'
foreach ($mapping in $groupMappings) {
# Iterate over mappings and set primary computers
$users = Get-ADUser -SearchBase $mapping.userOU -Filter { Enabled -eq $true } -Properties $pcAttrib
$machines = Get-ADComputer -SearchBase $mapping.machineOU -Filter { Enabled -eq $true }
$users = $users | Foreach-Object {
if (Compare-Object $_.$pcAttrib $machines) { $_ }
}
if ($users) {
Write-Host ('Setting {0} for the following users:' -f $pcAttrib)
$users.DistinguishedName
Write-Host 'Machines to be added for each user:'
$machines.DistinguishedName
$users | Set-ADUser -Clear $pcAttrib
if ($machines) {
$users | Set-ADUser -Add @{ $pcAttrib = $machines.DistinguishedName }
}
}
}
Write-Host 'User primary computer mapping complete.'
Stop-Transcript
@AfroThundr3007730
Copy link
Author

I wanted certain groups of users to only roam on computers in their section, so this is the result.

This can be easily modified to use security groups instead, depending on your AD setup.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment