Script for Enable-RemoteMailbox based off AD and CSV

I’m trying to create a script that will import info from a csv, take the “first name” from column C and the “last name” from column D, get the AD objects (Name and username) associated with those names and put them into an output csv file. (more for records sake, but also for the next step)

Then, from that output file I want to run the following command, or something like it:

$Users = Import-csv C:\Temp\Userlist.csv
$Users | ForEach-Object {Enable-RemoteMailbox -identity $_.userprincipalname -RemoteRoutingAddress ($_.samaccountname+'@TENANT.mail.onmicrosoft.com')}

Any help on putting all this together would be appreciated.

Currently I have to run the below command for every new user that needs a mailbox. It’s effective, but time consuming when theres more than 10 new users in my list.

$username = Read-Host 'What is the username?'
Enable-RemoteMailbox $username -alias $username -RemoteRoutingAddress $username@TENANT.mail.onmicrosoft.com
Enable-RemoteMailbox -identity $username -archive
$UserList = Import-csv C:\Temp\Userlist.csv
$UserList | % {
    Enable-RemoteMailbox $_ -alias $_ -RemoteRoutingAddress "$_@TENANT.mail.onmicrosoft.com"
    Enable-RemoteMailbox -identity $_ -archive
}

Thank you.

That helps for the second part of the script but doesn’t query AD for the correct username based off the 2 columns in the original csv.

Any ideas?

you should approach this in 2 steps.

first you need to come up with the appropriate command structure for your ad query.

the issue you will run into is users with duplicative names so i really suggest you don’t utilize this.

however… you can perform something along get-aduser -filter {givenname -eq $firstname -and surname -eq $lastname}

you really should try to use an identifier that is guaranteed to be distinct…

Thank you David,

I agree that it should be done in 2 steps. I wanted it to output the get-aduser into a csv for QA purposes just in case it grabs the wrong user in the event there are duplicate names. Fortunately the consequences of a duplicate name in AD is not bad since this is only creating a mailbox in the local exchange, and not assigning a license in O365. Worst case, it creates a mailbox in Exchange for someone that can’t get to it anyway. I will definitely work towards getting a unique identifier instead since that is a much better option.

I will work on testing your suggestion and see if that accomplishes the task at hand.