How do I retrieve a list of primary users of computers

7.8k views Asked by At

How do I pipe the objects of a CSV file into the DeviceName parameter of Get-CMUserDeviceAffinity?

I have a list of computers. I'd like to generate a list of the primary users for each of the computers in this list. I'm using powershell and the SCCM module and so far I've tried a one-liner as well as something more wordy to no avail.

One-Liner fail:

Import-CSV C:\temp\computerlist.csv |  Get-CMUserDeviceAffinity -DeviceName $($_.Name)

Script fail:

$Computers = C:\computers.CSV
   ForEach ($Computer in $Computers) {
       Get-CMUserDeviceAffinity -DeviceName $_.Name

Results of both fails:

Cannot validate argument on parameter 'DeviceName'. The argument is null or empty. Provide
an argument that is not null or empty, and then try the command again.
At line:1 char:77
+ ... p\computerlist.csv |  Get-CMUserDeviceAffinity -DeviceName $($_.Name)
+                                                                ~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-CMUserDeviceAffinity], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ConfigurationManagement.Cmdlets.Collections.C
   ommands.GetUserDeviceAffinityCommand
2

There are 2 answers

1
Martin Brandl On BEST ANSWER

You are using the automatic pipeline varaible $_ whereas you don't have a pipeline object in your foreach loop. Just use $Computer instead:

$Computers = C:\computers.CSV
   ForEach ($Computer in $Computers) {
       Get-CMUserDeviceAffinity -DeviceName $Computer.Name
}
0
Bifeng Dong - MSFT On

Assuming your csv is like this
enter image description here

You can try to use below PowerShell script:

$Computers = Import-Csv C:\computerlist.CSV
   ForEach ($Computer in $Computers) {
      $Name = (Get-CMUserDeviceAffinity -DeviceName $Computer.Name).uniqueusername
      write-host "$($computer.name) ------> $($Name) "
}

The Output:
enter image description here