AzureADuser foreach question

Hi All

the goal of this to retrieve the objectID from a disabled user and to remove this user from all the azureAD groups.
In order to do this I need to get the object from the user first

when using this as a standalone command

get-AzureAdUser -SearchString "SamaccountName" |select objectId, Displayname, UserPrincipalName |export-csv c:\temp\AzureAdUsers.csv -notypeinformation -append  

it works like a charm
however when I want to use it in a foreach I get the below mentioned error

$users = import-csv C:\users\Public\Documents\CSV\ToRemove.csv
foreach($user in $users){
get-azureAdUser -SearchString "$user.SamAccountName" |select Objectid,displayname,UserPrincipalName |export-csv c:\temp\azureADusers.csv -NoTypeInformation -append
}

and the error is this
get-azureAdUser : Error occurred while executing GetUsers
Code: Request_UnsupportedQuery
Message: Unsupported or invalid query filter clause specified for property ‘userPrincipalName’ of resource ‘User’.
any Idea on how to get this sorted out?

Only a base variable can be expanded in a string. Since you need to reference the samaccountname property surround it with a subexpression. So change

“$user.samaccountname”

to

”$($user.samaccountname)”

THanks Doug,
an additional question that pops in my mind. A user can be member in multiple groups and this will as such also be multiple times populated in my export is there a way that I Can use distinct to just use a given user.objectid once? in the following code

$azureadgroups = Get-AzureADGroup
$users = import-csv c:\temp\azureaduser.csv

foreach($user in $users){
        foreach($group in $azureadgroups){
    
        try{
        Remove-AzureADGroupMember -objectID $group.ObjectId -memberID $user.objectid
        }
        Catch{
        write-warning "$_"
      }
   }
}

thanks again for your help