SCCM 2012 User Device Affinity

I wrote a PowerShell script for my new SCCM 2012 environment that takes a list of users, and outputs both their Device Affinity pairings and the list of computers where they were the last logged on user. I’ve seen similar scripts, but nothing that accepted multiple usernames or combined both methods of looking up affinity.
The screenshot is from a dev environment where I don’t have a whole lot of data, but you get the idea.

Function Get-Affinity {
[parameter(Mandatory = $true)][string[]]$UserName,
$Domain = $env:USERDOMAIN,
$CMModulePath = "$env:SystemDrive\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1",

if (!(Get-Module -Name ConfigurationManage?)) { Import-Module $CMModulePath }
$SNPath = "$SiteName" + ":"
Set-Location "$SNPath"

foreach ($Name in $UserName) {
#For each user in the provided list...
$DeviceList = @()
foreach ($Device in (Get-CMUserDeviceAffinity -UserName "$Domain\$Name")) {
#For each device where the user is registered as the primary user...
$DeviceList += (Get-CMDevice -ID $Device.ResourceID).Name
User = $Name
PrimaryDevices = $DeviceList
LastLoggedOn = (Get-WmiObject -Namespace "root\sms\site_$SiteName" -ComputerName $SCCMServer -Query "select Name from sms_r_system where LastLogonUserName='$Name'").Name

Share this Story:
  • facebook
  • twitter
  • gplus


  1. Meeps
    2030 days ago

    This is great & I can run this for one user, but I’m having trouble feeding in a txt file of multiple users to output details for these. Any hints?

    • Ben
      2030 days ago

      I’ve changed jobs recently and don’t have access to test this anywhere, but it should be straight forward. If your text file is 1 username per line, something like “Get-Affinity -UserName (Get-Content .\UserList.txt)” would do the trick. If not, please post the error message you’re getting and I’ll see what I can do to help.

Leave a comment