I’ve written the below script to get user and device affinity information. The script checks to see if its a user or device collection and switch runs against the right commands. It works, but for improvement purposes could i done something more efficiently ?
Function Get-CollectionAffinityData {
[cmdletbinding()]
param (
[Parameter(Mandatory=$true)]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
[string]
$Collection
)
$script:Collection = Get-CMCollection -Name $Collection
switch ($script:Collection.CollectionType)
{
0 { "Not supported in this script" }
1 { $users = Get-CMUser -CollectionName $script:Collection.name
$script:array = @()
$users | foreach {
$data = New-Object PSObject -Property @{
PrimaryUser = $_.SMSID
PrimaryDevices = if (($_ = Get-CMUserDeviceAffinity -UserName $_.SMSID).ResourceName -eq $null) { '$Null' } else { $_.ResourceName }
LastClientCheckDate = ForEach ($y in $_.ResourceName ) { ( Get-CMDevice -Name $y ).LastClientCheckTime.ToShortDateString() }
}
$script:array += $data
}
} #End of switch "1"
2 { $Devices = Get-CMDevice -CollectionName $script:Collection.Name
$script:array = @()
$users = $devices | foreach { $_.UserDomainName + "\" + $_.UserName } | foreach { Get-CMUser -Name $_ }
$users | foreach {
$data = New-Object PSObject -Property @{
PrimaryUser = $_.SMSID
PrimaryDevices = if (($_ = Get-CMUserDeviceAffinity -UserName $_.SMSID).ResourceName -eq $null) { '$Null' } else { $_.ResourceName }
LastClientCheckDate = ForEach ($y in $_.ResourceName ) { ( Get-CMDevice -Name $y ).LastClientCheckTime.ToShortDateString() }
}
$script:array += $data
}
} #End of switch "2"
}
echo $script:array
}#End of function
output looks like this:
PrimaryDevices LastClientCheckDate PrimaryUser
{DEVICE1, DEVICE2} {20/04/2016, 08/03/2016} DOMAIN\USER1, DOMAIN\USER2
DEVICE3 01/03/2016 DOMAIN\USER3