How can I grab a user's logonworkstations list and remove all entries that match a csv listing

Viewed 116

WorkstationList.csv has 3 separate columns with different names. Trying to use a column "retired" that has a list of retired logonworkstations names and match them to a users current list. If there is a match then delete from the users logonworkstation list.

$defaultWorkstationslist = Import-Csv -Path '[workstationList.csv]'


$olist = Get-Aduser $user-Properties LogonWorkstations | Select LogonWorkstations
$newlist = ''

foreach ($o in $olist){
    foreach ($r in $defaultWorkstationslist.retired){
        
        if ($o -ne $r){
            $newlist += $o
        } else {
            continue
        }
    }
}

Set-ADUser $user -logonWorkstations $newlist

Output:
Set-ADUser : The format of the specified computer name is invalid
[redacted]:36 char:1
+ Set-ADUser $user-logonWorkstations $newlist
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (user:ADUser) [Set-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:1210,Microsoft.ActiveDirectory.Management.Commands.SetADUser
1 Answers

According to the Set-ADUser Docs for this specific parameter:

To specify more than one computer, create a single comma-separated list. You can identify a computer by using the Security Account Manager (SAM) account name (sAMAccountName) or the DNS host name of the computer. The SAM account name is the same as the NetBIOS name of the computer.

We can assume that, if the user has this property set, it would be a string with each computer comma separated (computer1,computer2...). Following that assumption, we can first test if the user has that property set, then split the value by comma and lastly filter each value against the $defaultWorkstationslist.retired array.

Important Note, this should work as long as the column Retired from your Csv has computer names using the SAM account name or NetBIOS name of the computer as stated in the docs.

$user = 'someuser'
$defaultWorkstationslist = Import-Csv -Path '[workstationList.csv]'
$aduser = Get-ADUser $user -Properties LogonWorkstations
# if this user has the attribute set
if($wsList = $aduser.LogonWorkstations) {
    # split the string by comma and then use filtering technique to exclude those values that
    # exists in the `$defaultWorkstationslist.retired` array.
    $allowedList = ($wsList.Split(',').Where{ $_ -notin $defaultWorkstationslist.retired }) -join ','
    Set-ADUser $user -LogonWorkstations $allowedList
}
  • For filtering we can use the .Where intrinsic method, where the current object in the pipeline is represented with $_ ($PSItem)
  • For testing if an element $wsList is contained in $defaultWorkstationslist.retired we can use Containment operators.
Related