This is running through every line in your CSV file, and so all $Firstname and so forth will contain at the end are the values form the last line. You probably need ALL of your code within the ForEach loop, not just this portion.
The problem is this does not seem to work. I have entered a user that exists, but the result I get is my own error of Not Found.
Assistants would be grateful.
So what I’m attempting to create is a script that will create a new user, but then wait for that user to be created in 365, before adding the correct groups to the user.
I have managed to piece together what I wanted, but I now need it to loop until the user is found before continuing.
Check the output of Get-MsolUser cmdlet. I never used it, but guessing it returns an object and not user as string. Then your comparison with $UserName won’t work. you will have to do $User.Name -eq $UserName (if Name is the property which exposes user name)
You didn’t say what commands you are using to get the user into O365 but I use new-remotemailbox, and then kick off a delta sync. I have found that it takes about 90 seconds from when I run the delta sync for the user to show up in O365. Once I run the delta sync, I put in a sleep timer for 90 seconds and then do the following:
Do
{
Get-MsolUser -UserPrincipalName $upn -ErrorAction SilentlyContinue -ErrorVariable o365error | Out-Null
} #enddostatement
Until (!$o365error)