Create a read-only user in Office365

This is the first of the 2 series blog. In this, I’ll explain how to do create a read-only Office365 User, directly from the client PowerShell. And then there’s a complete code snippet to achieve the same from a C# Console App in the 2nd part of this blog[Coming soon]. Before delving deep, I would like to highlight the fact, that you’ll NOT be charged for this User a/c by Microsoft. We’ll be barely creating a User, not assigning any license to it.

The entire process can be broadly classified into 4 major steps:

  1. Authenticate using existing administrator’s userID & password
  2. Create a new User with a randomly generated password
  3. Assign the role, “Service Support Administrator
  4. Assign the RoleGroupMember, “View-Only Organization Management” [Exchange]

PowerShell

Requirement:

SharePoint Online Management Shell with all its dependencies.

Authenticate using existing administrator’s userID & password

Open Windows PowerShell and enter the cmdlet,

"Connect-MsolService".

A dialogue will pop-up seeking the userId & password.

Provide an administrators credential here. Note, you’ll not be notified for wrong userID or password. In the event of providing wrong credential, the following cmdlets will refuse to run. So, make sure, that the credential is correct.

Create a new User with a randomly generated password

Once, the authentication is done, we’ll then create a new Office365 user. We’ll be providing basic user details, like FirstName, LastName, LoginID [or, UserPrincipal(compulsory)]. But, we’ll never set the password. The password will be returned back to us, once the user has been created. Another important thing to note here is the password policy we’re enforcing here. First, we’re setting, “ForceChangePassword” to false. This implies that when the User will login for the very first time, he/she will not be prompted to change it. Next, we’re setting “PasswordNeverExpires“, to true which, is pretty much self-explanatory.

New-MSolUser -DisplayName “PK” -UserPrincipalName “pk@company.onmicrosoft.com” -FirstName “Piyush” -LastName “Singh” -ForceChangePassword $false -PasswordNeverExpires $true

Once the User has been created, its basic details like, UserPrincipalName, newly created Password, etc, will be displayed in the Shell. One can also specify their preferred password also by adding, “-Password “Password123” at the end of the above cmdlet.

Note: There can be multiple Users with identical DisplayName but not UserPrincipalName. It has to be unique.
 

Assign the role, “Service Support Administrator”

This is simple. We’ll be assigning the “Service Support Administrator” role to this newly created User.

Add-MSOLRoleMember –RoleName “Service Support Administrator” –RoleMemberEmailAddress pk@company.onmicrosoft.com

Assign the RoleGroupMember, “View-Only Organization Management”

This role group is specific to Exchange. The objective is to assign only view permission to this user. To accomplish this, we’ll execute the cmdlet, “Add-RoleGroupMember“. One problem, this cmdlet is not a part of SharePoint Online Management Shell. So we cannot directly run it. We have to, first, establish a remote connection to the Exchange Server, and temporarily import it’s commands to the local PowerShell session. Only then, we can execute the cmdlet, “Add-RoleGroupMember“. Once the job’s done, we should also remove this session. To know more about this, plz visit the site, http://technet.microsoft.com/en-us/library/dd335083(v=exchg.150).aspx

Since, here, we’ll be executing a series of commands, I have put it all down in a script file. Here’s the content,

$Cred = Get-Credential
$s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $cred -Authentication Basic –AllowRedirection
Import-PSSession $s
$memberLoginName = Read-Host ‘LoginID’
Add-RoleGroupMember -identity ‘View-Only Organization Management’ -member $memberLoginName
Remove-PSSession $s

Say, we saved the file in D drive, with the name, addExchngViewRole.ps1. So to execute the same, just run from powershell, D:/addExchngViewRole.ps1. A dialog box will be prompted (same as above). Here again, you need to specify the admin’s credential. Once validated, it will import the Exchange commands.

Next, you’ll be asked to provide the PrincipalID or LoginName of the User who will be assigned to the RoleGroup, View-Only Organization Management [in this case, pk@company.onmicrosoft.com]. After that the user will be added to the given group and the current session will be removed from your machine, as per Microsoft’s guideline.

Note: ConnectionUri has been fixed to https://ps.outlook.com/powershell. This is valid for Exchange Online only. If you’re using on-premise, plz replace the url with this one, http:///PowerShell/.

Sideloading of apps is not enabled on this site

SideLoading of apps is disabled by default on SharePoint sites. So in order to publish our app directly from visual studio, we need to enable this option. However, do remember that Sideloading apps is a developer/test feature not intended for production use.Before proceeding further please make sure that you have already installed the Sharepoint Online Management Shell. Next follow the steps described below:-

Enable SideLoading

* Save the following code to your machine as “EnableSideLoading.ps1“.


$programFiles = [environment]::getfolderpath("programfiles")

add-type -Path $programFiles'\SharePoint Online Management Shell\' + `
  'Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll'

Write-Host `
  'To enable SharePoint app sideLoading, ' + `
  'enter Site Url, username and password'
 
$siteurl = Read-Host 'Site Url'
$username = Read-Host "User Name"
$password = Read-Host -AsSecureString 'Password'
 
if ($siteurl -eq '') {
    $siteurl = 'https://mytenant.sharepoint.com/sites/mysite'
    $username = 'me@mytenant.onmicrosoft.com'
    $password = ConvertTo-SecureString -String 'mypassword!'`
                -AsPlainText -Force
}
$outfilepath = $siteurl -replace ':', '_' -replace '/', '_'
 
try
{
    [Microsoft.SharePoint.Client.ClientContext]$cc = `
      New-Object Microsoft.SharePoint.Client.ClientContext($siteurl)
 
    [Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spocreds = `
      New-Object `
      Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
 
    $cc.Credentials = $spocreds
    $sideLoadingEnabled = `
    [Microsoft.SharePoint.Client.appcatalog]::IsAppSideloadingEnabled($cc);
    
    $cc.ExecuteQuery()
    
    if($sideLoadingEnabled.value -eq $false) {
        Write-Host -ForegroundColor Yellow `
          'SideLoading feature is not enabled on the site:' $siteurl
        $site = $cc.Site;
            $sideLoadingGuid = `
           new-object System.Guid "AE3A1339-61F5-4f8f-81A7-ABD2DA956A7D"
            $site.Features.Add($sideLoadingGuid, $false, `
            [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None);
            $cc.ExecuteQuery();
           Write-Host -ForegroundColor Green `
          'SideLoading feature enabled on site' $siteurl
    }
    
    Else {
        Write-Host -ForegroundColor Green `
          'SideLoading feature is already enabled on site' $siteurl
    }
}
 
Catch { 
    Write-Host -ForegroundColor Red `
      'Error encountered when trying to enable SideLoading feature' `
      $siteurl, ':' $Error[0].ToString();
}
* Execute “EnableSideLoading.ps1” from PowerShell.
* Provide your Credentials.
* That’s it. You’ll now be able to install app directly from Visual Studio.

Disable SideLoading

Once your job  is done, make sure to disable this option. To do that run the following script from PowerShell just as it has been described above.

$programFiles = [environment]::getfolderpath("programfiles")

add-type -Path $programFiles'\SharePoint Online Management Shell\' + `
 Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll'

Write-Host 'To disable sideLoading, enter Site Url, username and password'
 
$siteurl = Read-Host 'Site Url'
 
$username = Read-Host "User Name"
 
$password = Read-Host -AsSecureString 'Password'
 
if ($siteurl -eq '') {
    $siteurl = 'https://mytenant.sharepoint.com/sites/mysite'
    $username = 'me@mytenant.onmicrosoft.com'
    $password = ConvertTo-SecureString -String 'mypassword!' `
      -AsPlainText -Force
}
 
Try {
    [Microsoft.SharePoint.Client.ClientContext]$cc = `
    New-Object Microsoft.SharePoint.Client.ClientContext($siteurl)
 
    [Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spocreds = `
    New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
 
    $cc.Credentials = $spocreds
 
    $site = $cc.Site;
    
    $sideLoadingEnabled = `
    [Microsoft.SharePoint.Client.appcatalog]::IsAppSideloadingEnabled($cc);
    
    $cc.ExecuteQuery()
    
    if($sideLoadingEnabled.value -eq $false)
    {
      Write-Host -ForegroundColor Green `
        'SideLoading is alreday disabled on site' $siteurl
        }
       else
       {
      Write-Host -ForegroundColor Yellow `
        'Disabling SideLoading feature on site' $siteurl
      $sideLoadingGuid = `
        new-object System.Guid "AE3A1339-61F5-4f8f-81A7-ABD2DA956A7D"
      $site.Features.Remove($sideLoadingGuid, $true);
      $cc.ExecuteQuery();
      Write-Host -ForegroundColor Green `
        'SideLoading disabled on site' $siteurl
        }

} catch {
    Write-Host -ForegroundColor Red `
      'Error encountered when trying to disable side loading features' `
      $siteurl, ':' $Error[0].ToString();
}
 

For further details, visit the following site:
http://blogs.msdn.com/b/officeapps/archive/2013/12/10/enable-app-sideloading-in-your-non-developer-site-collection.aspx

Get Available PowerShell Commands for SharePoint on Client-Side

Needless to say, that on Client Side, we get a limited scope of running various SharePoint commands. As a result there aren’t much cmdlets for the Client Side. So how do you know what are the available commands that might come handy while executing cmdlets remotely? Simply run the following command in PowerShell or SharePoint Online Management Shell.
get-command | Where-Object { $_.ModuleName -eq "Microsoft.Online.SharePoint.PowerShell" }

A sample list of available cmdlets are displayed in the following screenShot.

Get all Licensed Office 365 users using PowerShell

Sometimes, we might need to view all the Licensed Users within a Office365 tenant. So here, I am going to demonstrate how to get all the users for any further analysis.

But before we delve into this plz make sure that you have all the components installed on the machine to run SharePoint Online Management Shell and  the cmdlet, Connect-MsolService. You can refer this blog post also for any assistance: https://realmpksharepoint.wordpress.com/2014/07/10/install-sharepoint-online-management-shell-on-client-side/

Following are the steps involve to perform this task:

  • Open the SharePoint Online Mangement Shell in Administrator mode.
  • Type in Connect-MsolService. When the window pops up, enter your corresponding administrator credentials.
  • If no error message is thrown then your credentials are validated.
  • In case you’re interested in getting all the available properties for the user object returned by the Get-MsolUser, then type in the cmdlet,
    Get-MsolUser | Get-MsolMember | Out-GridView
    

    The following screen will be displayed.

  • As you can see that there’s a property called isLicensed, we’re now gonna use this property in our next cmdlet to get all the Licensed Office365 users only, by running the command,
    Get-MsolUser | Where-Object { $_.isLicensed -eq "TRUE" }
    

  • Finally, you can also export this information to a csv file. To do this, run this command,
    Get-MsolUser | Where-Object { $_.isLicensed -eq "TRUE" } | Select-Object UserPrincipalName, DisplayName, Country, Department, ValidationStatus | Export-Csv c:\LicensedUsers\LicensedUsers.csv
    

  • You can also view all the properties by running the command,
    Get-MsolUser | Where-Object { $_.isLicensed -eq "TRUE" } | Export-Csv c:\LicensedUsers\LicensedUsers.csv
    

The last 2 commands will not generate any message on the shell, but you can check the file at your given location.

Thanks…

Install SharePoint Online Management Shell on Client-Side

This particular job caused quite a bit of trouble. Though, the objective was just to download and install the SharePoint Online Management Shell, the issues arose due to various dependencies. I have tried to list down the various steps involved in this operation below

System Requirements:

    • Supported Operating System.
      • Windows 7 Service Pack 1,
      • Windows 8,
      • Windows Server 2008 R2 SP1,
      • Windows Server 2008 Service Pack 2,
      • Windows Server 2012
  • PowerShell 3.0

Update PowerShell from 2.0 to 3.0

If you’re running the PowerShell version < 3.0 then you need to update it to 3.0.  You can check the version of the PowerShell by running the following command in the shell.

$PSVersionTable.PSVersion

The ScreenShot above displays a PowerShell of version 3.0. You may get version 2.0 or if you can also get an error message stating, that the variable does not exist then, it is safe to assume that the engine is version 1.0. If your engine is 3.0 or higher you can skip this segment.

Next, download the latest Windows Update from the url, http://www.microsoft.com/en-us/download/details.aspx?id=34595 and install it.

Install Instructions:
To install Windows Management Framework 3.0:
1.    Download the correct package for your operating system and architecture.

  • Windows 7 Service Pack 1
  • 64-bit versions: Windows6.1-KB2506143-x64.msu
  • 32-bit versions: Windows6.1-KB2506143-x86.msu
  • Windows Server 2008 R2 SP1
  • 64-bit versions: Windows6.1-KB2506143-x64.msu
  • Windows Server 2008 Service Pack 2
  • 64-bit versions: Windows6.0-KB2506146-x64.msu
  • 32-bit versions: Windows6.0-KB2506146-x86.msu

2.    Close all Windows PowerShell windows.
3.    Uninstall any other versions of Windows Management Framework 3.0.
4.    Run the MSU file that you downloaded.
For information about troubleshooting the installation, see the Release Notes.

To uninstall Windows Management Framework 3.0:
5.    In Control Panel/Programs/Uninstall a program/View installed updates, locate and uninstall the following installed Windows Update:

  • KB2506143 – for Windows 7 SP1 and Windows Server 2008 R2 SP1
  • KB2506146 – for Windows Server 2008 SP2

SharePoint Online Management Shell

Download and install SharePoint Online Management Shell from the url, http://www.microsoft.com/en-us/download/details.aspx?id=35588 

Run the Shell

Open the SharePoint Online Management Shell

And type the command Connect-MsolService and press enter. If everything is fine then, you’ll be shown the following screen

Otherwise, the following error message will be displayed!

Fix the Issue to run Connect-MsolService, PowerShell command

If you can run the command, Connect-MsolService, then everything is fine and you can skip this step and run your commands successfully.

To successfully run the Connect-MsolService PowerShell command, you need to:
1.    Find out what bitness your operating system is (x86 / 32-bit OR x64 / 64-bit). See Microsoft’s “Is my PC running the 32-bit or 64-bit version of Windows?” article for help.
2.    If necessary, install the appropriate bitness version of PowerShell 3.0 (which I hope we just did already)
Note 1: Windows6.0 is Windows Vista and Windows6.1 is Windows 7
Note 2: If you get a message of “The update is not applicable to your computer.” during the install then either you downloaded the wrong version of you already have it installed
3.    Install the appropriate bitness version of the Microsoft Online Services Sign-In Assistant for IT Professionals
4.    Install the appropriate bitness version of the Windows Azure Active Directory Module for Windows PowerShell
Note: If you get an error of  “In order to install Windows Azure Active Directory Module for Windows PowerShell, you must have Microsoft Online Services Sign-In Assistant version 7.0 or greater installed on this computer.” and a resulting failed install, install the Microsoft Online Services Sign-In Assistant for IT Professionals BETA (you shouldn’t need to uninstall the normal version but I would recommend it).
5.    Run the appropriate bitness version of PowerShell
6.    Run the Import-Module MSOnline PowerShell command
7.    Finally, run the Connect-MsolService PowerShell command

You should now be able to see the login screen.
 

Finally, it’s done!!

[Edit]
It has been noted that on some machines, even though the command runs successfully directly from the PowerShell, the same cmdlet throws the “cmdlet not supported” error when trying to execute it from within a C# application. To tackle it:

Copy the folders called MSOnline and MSOnline Extended from
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ 

to the folder
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\

And then in PS run the Import-Module MSOnline, and it will automatically get the modules.