Create user office 365 if not exist RRS feed

  • Question

  • Hi;

    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  ..\*.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: XXXX@XXX.com
    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

    How do not show this error message from the output ?


    • Moved by Bill_Stewart Tuesday, March 25, 2014 2:44 PM Abandoned
    Friday, October 11, 2013 7:06 AM

All replies

  • Hello Djamel,

    there are basically two ways to go about this: The quick and dirty way and the more wise, but more time-intensive way.

    # Quick and Dirty:
    # Append this to command
    -ErrorAction 'SilentlyContinue'
    # A bit more effort:
        [Your command]
        [If this one error, ignore it, otherwise report it]

    Quick and dirty takes half a minute, but means you won't be shown any errors generated by Get-MsolUser. For more info on just how the smarter but more time-intensive solution works, use:

    Get-Help about_try


    There's no place like

    Friday, October 11, 2013 7:16 AM
  • This is the simple way to deal with one off error situations.

    Import-csv  ..\*.csv |
    			New-MsolUser @newUser -ErrorAction Stop
    			# we want to display the actual error.
    			Write-host "$_"

    Using a splat makes the code much easier to read.

    This code has been tested on Office 365


    • Edited by jrv Friday, October 11, 2013 8:33 AM
    • Proposed as answer by Mike Laughlin Sunday, October 13, 2013 1:08 AM
    Friday, October 11, 2013 8:32 AM