How to set the msExchQueryBaseDN attribute for users via powershell

I was working in the lab today trying to debug a reproduction of an OWA hosting issue and I had the need to set the msExchQueryBaseDN for 10,000 users. Typically you can use Poweshell with the get-user | set-user commands to access mailbox properties for stamping purposes, however the msExchQueryBaseDN attribute is a user based attribute. Here are two ways you can do it:

How to set an attribute for one user via powershell
$user = ([ADSI]"LDAP://OU=MyOU,DC=Company,DC=com").psbase;
$user.Properties["msExchQueryBaseDN"].Value = "CN=User,OU=MyOU,DC=Company,DC=com";
$user.CommitChanges();

How to set an attributes for a group of users in an OU via Powershell
get-mailbox -resultsize unlimited | Foreach { $dn = "LDAP://" + $_.distinguishedname;$obj = [ADSI]$dn;$obj.msExchQueryBaseDN = "DC=domain,DC=com";$obj.setinfo()}

For troubleshooting purposes

If you are having problems and you are not seeing anything displayed in powershell you can run the following command:

 C:\>get-mailbox | Foreach { $dn = "LDAP://" + $_.distinguishedname; write-host $dn}

I have four mailboxes in my lab and here you can see that four results have been displayed.

LDAP://CN=OabUser1,OU=Owa,DC=oablab,DC=local
LDAP://CN=OabUser2,OU=Owa,DC=oablab,DC=local
LDAP://CN=OabUser3,OU=Owa,DC=oablab,DC=local
LDAP://CN=OabUser4,OU=Owa,DC=oablab,DC=local

NOTE: Running Get-Mailbox *userName* | fl msExchQueryBaseDN will not return any results as this parameter is not returned in powershell.

This little bad boy stamped 10,000 users in less than 2 minutes.

Dave