Link to home
Create AccountLog in
Avatar of ndalmolin_13
ndalmolin_13Flag for United States of America

asked on

Using Powershell to check to see if an Office 365 account exists for a user. If it does not exist, then create it.

Hello Experts,
Our organization is moving to Office 365.  I have a list (csv file) of over 100 users.  My csv file has the following columns:
UserPrincipalName, LastName, FirstName, DisplayName

Some of the users in the csv file have accounts in Office 365 and some do not.  I would like to use Powershell to go through the list.  If a user has an Office 365 account, then Powershell will display a message stating that the user already exists in Office 365.  If the user does not have an Office 365 Account, Powershell will create an account for that user.  Here is what I’m thinking (I’ve already connected to Office 365 and MSOL services in Powershell):

$Accounts = Import-csv d:\migrations\health\HealthKingTest.csv
ForEach ($account in $accounts)
$AccountExists = Get-MsolUser -UserPrincipalName $account.UserPrincipalName
If ($AccountExists -ne $Null) {Write-host "$($Account.Displayname) exists in Office 365"}
Else {New-MsolUser -UserPrincipalName $Account.UserPrincipalName, -LastName $Account.LastName, -FirstName $Account.FirstName, -DisplayName $Account.Displayname}

When I run this, I get the following errors and it has to do with creating the new user:

Get-MsolUser : User Not Found.  User:
At C:\PS_Scripts\test11512.ps1:4 char:30
+ $AccountExists = Get-MsolUser <<<<  -UserPrincipalName $account.UserPrincipal
    + CategoryInfo          : OperationStopped: (:) [Get-MsolUser], MicrosoftO
    + FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.UserN
New-MsolUser : Cannot convert 'System.Object[]' to the type 'System.String' req
uired by parameter 'UserPrincipalName'. Specified method is not supported.
At C:\PS_Scripts\test11512.ps1:6 char:38
+ Else {New-MsolUser -UserPrincipalName <<<<  $Account.UserPrincipalName, -Last
Name $Account.LastName, -FirstName $Account.FirstName, -DisplayName $Account.Di
    + CategoryInfo          : InvalidArgument: (:) [New-MsolUser], ParameterBi
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.Online.Administr

If some of you Office 365 and Powershell experts can take a look at this and point me in the right direction, I would greatly appreciate it.

Avatar of justinoleary911
Flag of United States of America image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account