ForEach-Object loop containing Get-ADUser and filter
<p>My company has a script to handle licenses for O365, and current it assigns the same country to all users such as</p>

<pre><code>$Location = "US"
$E2Users = Get-ADGroupMember lg.o365.Office | Select SamAccountName
$E2Users | ForEach-Object{
$UPN = $E2Users[$Counter].SamAccountName + "@company.com"
Set-MsolUser -UserPrincipalName $UPN -UsageLocation $Location
##lots of other code
</code></pre>

<p>I need to retrieve the country of each user and use that rather than the string.  I've set up a little test to ensure I have the correct country by using out-put to see the results, however I can't seem to wrap my head around it to get it working.  I saw the $username = $_ in another forum and tried to use it.</p>

<pre><code>$E2Users = Get-ADGroupMember lg.o365.Office | Select SamAccountName
$E2Users | ForEach-Object{
$username = $_
$Location = Get-ADUSer -filter {samaccountname -like "*$username*"} -properties * | Select country
write-output $Location
}
</code></pre>

<p>Or do I even need a filter? Using the following gives me output of countries, but how to ensure they are matched up correctly with each user.  Some resulting lines had blanks using country or c, and when checking the user account those attributes have values.</p>

<pre><code>$E2Users = Get-ADGroupMember lg.o365.Office.PlanK1 | Select SamAccountName
$E2Users | ForEach-Object{
$Location = Get-ADUSer -filter * -properties * | Select country
write-output $Location
}
</code></pre>

<p>The end result would be something that looks like the following</p>

<pre><code>$E2Users = Get-ADGroupMember lg.o365.Office | Select SamAccountName
$E2Users | ForEach-Object{
$UPN = $E2Users[$Counter].SamAccountName + "@company.com"
$Location = Get-ADUSer -filter {not sure what to use} -properties * | Select country    
Set-MsolUser -UserPrincipalName $UPN -UsageLocation $Location
##lots of other code
</code></pre>

<p>What am I missing and not understanding.  Thank you for any help.</p>