Export (0) Print
Expand All

Connect to Office 365 by using a single Windows PowerShell window

 

Topic Last Modified: 2014-10-10

Summary: Connect Windows PowerShell to Office 365 using a single Windows PowerShell window.

There’s a commercial airing on TV these days in which an adult moderator asks a group of elementary school children, “Who thinks more is better than less?” The children all say that more is better and, the narrator agrees with them. “It’s not complicated,” says the narrator. “More is better.”

To be honest, we hate to play Grinch to a bunch of elementary school children, but we have to do what we have to do: kids, you’re wrong. And it’s not complicated: the truth us, more is not always better than less.

Case in point? Using Windows PowerShell to manage Office 365. Each of the four Office 365 components (Office 365 users and licensing; SharePoint Online; Exchange Online; and Lync Online) require you to use a different connection method. With Office 365 and SharePoint Online, you typically start their respective management shells. With Lync Online, you start a local session of Windows PowerShell and then use the New-CsOnlineSession cmdlet to connect to Office 365. With Exchange Online, you start a local session of Windows PowerShell and then use the New-PSSession cmdlet to connect to Office 365.

That is complicated. But does any of it really matter to an Office 365 administrator?

As a matter of fact it does: with four different connection methods, it would appear that you need to use four different Windows PowerShell instances in order to manage all of Office 365. In other words, if you want to simultaneously manage Office 365, SharePoint, Exchange, and Lync management tasks, your computer desktop would need to look like this:

Four Windows PowerShell consoles running simultane

Like we said, more is not always better than less.

That’s obviously not an optimal situation (among other things, you can’t easily exchange data between those four PowerShell windows). That also brings up an important question: is there any way that you can manage Office 365, Lync, Exchange, and SharePoint using just one instance of Windows PowerShell?

You know, we were hoping that someone would ask that question.

Before we explain how to do just that – how to manage all of Office 365 from a single instance of Windows PowerShell, we should note that this article assumes that you have already set up your Office 365 account and that you have already downloaded and installed the software needed to manage Office 365 using Windows PowerShell. Assuming you’ve taken care of all that, then you just need to follow these seven steps in order to setup a single PowerShell window that enables you simultaneously manage Office 365, Lync, Exchange, and SharePoint

Technically you don’t have to start here: you could kick things off by starting the Windows Azure Active Directory management shell or the SharePoint Online management shell instead. But we’re going to start completely from scratch, which means running “plain old” Windows PowerShell as an administrator.

To run Windows PowerShell as an administrator, complete one of the following two procedures. If you’re running Windows 8, do this:

  1. Access the Charms bar, click Search, and then right-click Windows PowerShell. You can quickly access the Charms bar on any Windows 8 computer (touch screen or non-touch screen) by holding down the Windows key and pressing C.

  2. In the toolbar at the bottom of the screen, click Run as administrator.

  3. If the User Account Control dialog box appears, click Yes to verify that you want to run Windows PowerShell under administrator credentials.

If you’re running Windows 7 (or Windows Servers 2008 or Windows Server 2012) do this:

  1. Click Start, click All Programs, click Accessories, click Windows PowerShell, right-click Windows PowerShell, and then click Run as administrator.

  2. If the User Account Control dialog box appears, click Yes to verify that you want to run Windows PowerShell under administrator credentials.

And yes, you absolutely must run Windows PowerShell as an administrator. If you don’t, you’re going to get an error message similar to this when you try to import one of the Office 365 modules:

The specified module 'Microsoft.Online.SharePoint.Online.PowerShell' was not loaded because no valid module file was found in any directory.

Admittedly, that’s not the clearest error message ever written: the problem really isn’t that the module file couldn’t be found, the problem is that you can’t import a module unless you’re running as an administrator. The whole only way to remedy the situation is to close Windows PowerShell and restart it as an administrator.

After Windows PowerShell is up and running you should then verify that PowerShell is configured to run scripts. To do that, type this command from the PowerShell prompt and then press ENTER:

Get-ExecutionPolicy

Why do you need to do this? Well, if the execution policy is set to anything other than Unrestricted or RemoteSigned you’ll encounter an error similar to this when you try to import a module:

Import-Module : File C:\Program Files\Common Files\Microsoft Lync Server2013\Modules\lynconlineconnector\LyncOnlineConnectorStartup.psm1 cannot be loaded because running scripts is disabled on this system.

If you need to change the execution policy, use the Set-ExecutionPolicy cmdlet this command:

Set-ExecutionPolicy RemoteSigned

Note that you don’t have to exit and restart PowerShell; the change will take effect immediately.


The credentials object provides a safe and secure way to pass your user name and password to Office 365. To create a credentials object, type the following command from the Windows PowerShell prompt and press ENTER:

$credential = Get-Credential
NoteNote:
$credential is a variable that will store the credentials object. You don’t have to name the variable $credential, but doing so makes it easier to remember which variable contains the credentials object. (And that’s important, because we’ll reuse this variable several times.) That will also make it easier for you to follow our examples, because this article will always use $credential to represent the credentials object.

Windows PowerShell will then display a dialog box that looks like this:

Blank Credentials request dialog box.

Type your Office 365 user name in the User name box, using the format username@domainname (for example, kenmyer@litwareinc.onmicrosoft.com), then type your Office 365 password in the Password box and click OK:

Completed Credentials request dialog box.

Make sure the user account you specify has global administrator rights to Office 365. Otherwise your logon attempt will fail.

Note that, as is often the case, you won’t see any sort of confirmation that the credentials object was created. (Windows PowerShell typically tells you when things go wrong, but doesn’t always tell you when things go right.) If you want to verify that the credentials object was created, type the following at the Windows PowerShell prompt and then press ENTER:

$credential

You should then see something similar to this onscreen:

UserName                               Password
--------                               --------
kenmyer@litwareinc.onmicrosoft.com     System.Security.SecureString

One thing to keep in mind here is that the Get-Credential cmdlet only creates the credentials object; it does not authenticate you or otherwise verify that the user name and password you supplied are correct. For example, suppose you mistyped the user name as eknmyer@litwareinc.onmicrosoft.com. If you do that, Get-Credential will create a credentials object using that user name, and without checking to see if that is actually a valid user name. You will not know whether you have created a truly valid credentials object until you actually use that object to try to connect to Office 365.

Speaking of which, that’s exactly where we are in our process: we’re ready to connect to Office 365.


We’ll start by connecting to Office 365 itself. Again, we don’t have to start here; we can connect to the various components in any order. But we have to start somewhere, so ….

The first thing we need to do here is import the Office 365 module. To do that, run this command from the Windows PowerShell prompt:

Import-Module MsOnline

Admittedly, nothing will seem to have happened. If that worries, and if you want to verify that the module was imported, run this command:

Get-Module

Somewhere in the list of modules that are returned by this command you should see this:

Manifest  1.0   MSOnline    {Add-MsolForeignGroupToRole, Add-MsolG...}

If you see MSOnline listed, that means that everything went according to plan.

With the credentials object created (see Step 2: Create a Windows PowerShell credentials object) and with the MsOnline module loaded we can now connect to Office 365 by using the Connect-MsolService cmdlet and the following command:

Connect-MsolService -Credential $credential

Notice that all you have to provide is the credentials object ($credential). Based on those credentials, Office 365 will automatically connect you to the correct domain. You do not have to specify your domain name when running Connect-MsolService.

As usual, nothing will seem to have happen after the Connect-MsolService cmdlet finishes running. To verify that you really are connected to Office 365, run this command:

Get-MsolDomain

In return, you should get back something similar to this:

Name                         Status          Authentication
----                         ------          --------------
litwareinc.onmicrosoft.com   Verified        Managed

That’s one Office 365 component down, and three to go.


Next up: SharePoint Online. Once again, we need to import the correct Windows PowerShell module before we can do anything else. Fortunately, that’s easy to do; just type this command from the Windows PowerShell prompt and then press ENTER:

Import-Module Microsoft.Online.SharePoint.PowerShell
NoteNote:
When you do this you will probably see the following error message displayed onscreen:
WARNING: The names of some imported commands from the module 'Microsoft.Online.SharePoint.PowerShell' include unapproved verbs that might make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of approved verbs, type Get-Verb.
You can safely ignore this warning. The message appears because one of the SharePoint Online cmdlets, Upgrade-SPOSite, uses the verb Upgrade in its name; that verb is typically not used in Windows PowerShell cmdlet names. However, this deviation from the naming standard won’t hurt anything, and the cmdlet will run just fine.

In order to connect to SharePoint Online, you need to supply two pieces of information: your credentials, and the URL of your SharePoint admin site. The credentials part is easy: we’ve already stored that in the variable $credential (see Step 2: Create a Windows PowerShell credentials object). As for the URL of your admin site, that’s easy enough to determine as well. Suppose your Office 365 domain name is this:

litwareinc.onmicrosoft.com

To determine the admin site URL, do this:

  1. Start by using the prefix https://.

  2. Add the domain host portion of your domain name. For example, if your domain is litwareinc.onmicrosoft.com then your domain host name is litwareinc. If your domain name is contoso.onmicrosoft.com then your domain host name is contoso. Etc., etc.

  3. Add a hyphen (-) followed by admin.sharepoint.com: -admin.sharepoint.com.

In other words:

https:// + litwareinc + -admin.sharepoint.com = https://litwareinc-admin.sharepoint.com

After you’ve constructed the URL you can then use that URL and your credentials object to connect to SharePoint Online. Just call the Connect-SPOService cmdlet, using a command similar to this one:

Connect-SPOService -Url https://litwareinc-admin.sharepoint.com -credential $credential

To verify that the connection has been made, type the following command at the Windows PowerShell prompt and press ENTER:

Get-SPOSite

You should get back a list of all your SharePoint Online sites:

Url                                       Owner          Storage Quota
---                                       -----          -------------
http://litwareinc-public.sharepoint.com/                 1000
https://litwareinc.sharepoint.com/                       1000
https://litwareinc.sharepoint.com/search                 1000

But here’s the best part: your Office 365 commands (the ones described in Step 3: Connect to Office 365) will still work. (Try running Get-MsolUser and see for yourself.) That means that you can now manage both Office 365 and SharePoint Online from the same instance of Windows PowerShell. And that’s good. But it’s not quite good enough.


Connecting to Lync Online (and to Exchange Online) isn’t very hard, but it is a tiny bit trickier than connecting to Office 365 or to SharePoint Online. That’s because the Lync and Exchange cmdlets don’t get installed on your computer like the Office 365 and the SharePoint cmdlets do. Instead, each time you log on the appropriate cmdlets are temporarily copied to your computer. When you log off, those cmdlets are then removed from your computer.

In order to connect to Lync Online you must import the Lync module. To do that, run this command:

Import-Module LyncOnlineConnector

And then, after the module has been imported, run this command:

$lyncSession = New-CsOnlineSession -Credential $credential

When the command completes, you will see something similar to this onscreen:

Id Name       ComputerName    State  ConfigurationName    Availability
-- ----       ------------    -----  -----------------    ------------
1  Session1   webdir0a.onl... Opened Microsoft.PowerShell Available

What’s going on here? Well, what’s going on here is that we’ve created a remote PowerShell session. In this case, that means that we’ve connected to an instance of Windows PowerShell running on one of the Office 365 servers. However, just creating that session does very little for us. For example, try running this Lync Online command:

Get-CsMeetingConfiguration

That command is going to fail, and you’ll get the following error message:

Get-CsMeetingConfiguration : The term 'Get-CsMeetingConfiguration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Why did the call to Get-CsMeetingConfiguration fail? That’s easy: because the Get-CsMeetingConfiguration cmdlet doesn’t exist anywhere on your computer. Although we’ve made a connection to Office 365, we haven’t downloaded the scripts, cmdlets, and other items needed to manage Lync Online. To do that, we have to run this command:

Import-PSSession $lyncSession

When you import the Windows PowerShell session, you should see a progress bar similar to the following, a progress bar that reports on all the Lync Online management items being imported to your computer:

Lync Online progress bar.

When the progress bar disappears, you should then see output similar to the following:

ModuleType Version    Name               ExportedCommands
---------- -------    ----               ----------------
Script     1.0        tmp_swc5mp4v.1ck  {Copy-CsVoicePolicy, Disabl...

Now try running Get-CsMeetingConfiguration and see what happens. You should get back something similar to this:

Identity                        : Global
PstnCallersBypassLobby          : True
EnableAssignedConferenceType    : False
DesignateAsPresenter            : Company
AssignedConferenceTypeByDefault : True
AdmitAnonymousUsersByDefault    : True
RequireRoomSystemsAuthorization : False
LogoURL                         :
LegalURL                        :
HelpURL                         :
CustomFooterText                :
AllowConferenceRecording        : True

That’s more like it. All that’s left now is to get Exchange added to our Windows PowerShell session.


All we have to do now is connect to Exchange Online and we’ll be in business: we’ll be able to use a single Windows PowerShell session to manage Office 365, SharePoint Online, Lync Online, and Exchange Online. With that in mind, run this command, which creates a remote Windows PowerShell session with Exchange Online:

$exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $credential -Authentication "Basic" -AllowRedirection

Admittedly, this is a slightly more complicated command than some of the other commands we’ve run. But that’s OK, because you can copy the command and run it exactly as-is, even though there is a URI included in the command: https://outlook.office365.com/powershell-liveid/. However, that URI is always the same, regardless of the name of your domain. Therefore, copy, paste, run: it’s that easy.

NoteNote:
Why is the command for connecting to Exchange more complicated than the command to connect to Lync Online? Technically, it’s not: both commands do the exact same thing. However, the Lync Online team created its own cmdlet – New-CsOnlineSession – that hides some of the parameters (like the Authentication and AllowRedirection) used when connecting to Exchange. Instead of requiring you to type that information yourself, the Authentication and AllowRedirection parameters are effectively built into the New-CsOnlineSession cmdlet. You have to type those parameters when connecting to Exchange because Exchange uses the standard New-PsSession cmdlet to connect to Office 365. The disadvantage to that? You have a little more typing to do. The advantage? You don’t have to download and install an Exchange Online module.

When you connect to Exchange Online, you’ll see a warning message similar to this:

WARNING: Your connection has been redirected to the following URI: "https://pod51035psh.outlook.com/powershell-liveid?PSVersion=4.0"

You don’t have to worry about that message either: it simply tells you that Office 365 has authenticated you and pointed your session towards your Office 365 domain. All you have to do now is import this remote session, just like we did with Lync:

Import-PSSession $exchangeSession

And then, if all goes well, you’ll see something similar to this onscreen:

WARNING: The names of some imported commands from the module 'tmp_nweiqjvl.geu' include unapproved verbs that might make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of approved verbs, type Get-Verb.

ModuleType Version  Name             ExportedCommands
---------- -------  ----             ----------------
Script     1.0      tmp_nweiqjvl.geu {Add-AvailabilityAddressSpace...

Now try running this command:

Get-AcceptedDomain

In return, you should see information about your Exchange Online domain:

Name            DomainName          DomainType      Default
----            ----------          ----------      -------
litwareinc.com  litwareinc.com      Authoritative   True

If that command succeeds, that means you can now manage all of Office 365 from a single PowerShell session.


You might be wondering why we even bothered to include this step. After all, how hard can it be to end a Windows PowerShell session: you just close the PowerShell window and everything disappears. Case closed.

And that’s true: everything will disappear. However, that doesn’t necessarily mean that your remote sessions have been properly disposed of. For example, even if you close the PowerShell window your Lync Online remote connection will remain active for the next 15 minutes or so. That could prove to be a problem. Why? Because Lync Online limits the number of simultaneous connections that any one person or any one domain can have open. With Lync Online, an individual administrator can have, at most, three open connections at one time, while a domain can have a maximum of nine open connections. If you log on to Lync Online and then exit without properly closing the session, that session remains open for the next 15 minutes or so. As a result, that’s one fewer connection available to you or to other administrators in your domain.

Which means that this time the kids are right: having more available connections is better than having less available connections. In turn, that means that it’s a good idea to close your sessions once you’re done with them.

To start with, let’s close the remote sessions opened for Lync Online and Exchange Online. Before we do that, run this command:

Get-PSSession

The Get-PSSession cmdlet should show you that you have at least two remote sessions open, one for Lync and one for Exchange (it’s possible you could have more than two remote sessions running, depending on whether you’ve used this instance of PowerShell to connect to something else besides Office 365). At any rate, you should see something similar to the following:

Id Name     ComputerName    State   ConfigurationName    Availability
-- ----     ------------    -----   -----------------    ------------
 2 Session2 webdir0a.onl... Opened  Microsoft.PowerShell Available
 3 Session3 pod51035psh.... Opened  Microsoft.Exchange   Available

To close these two sessions, use these commands, the first to close Lync, and the second to close Exchange:

Remove-PSSession $lyncSession
Remove-PSSession $exchangeSession

If you now run the Get-PSSession cmdlet you should see nothing at all (unless, of course, you have other remote sessions up and running):

Windows PowerShell console with no remote sessions
NoteNote:
If you’d prefer to close all your remote sessions at the same time, you can use this command:
Get-PSSession | Remove-PSSession

If you now try running a Lync Online or an Exchange Online cmdlet (for example, Get-CsMeetingConfiguration) you should get this error message:

Get-CsMeetingConfiguration : The term 'Get-CsMeetingConfiguration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

We get that error message because the Lync Online and the Exchange Online cmdlets were deleted when we closed the remote sessions.

To close the SharePoint Online session, type this command:

Disconnect-SPOService

Again, it won’t look like anything has happened. But if you try to run the Get-SPOSite cmdlet you’ll get this error message:

get-sposite : No connection available. Use Connect-SPOService before running this CmdLet.

You can’t retrieve site information because you’re no longer connected to SharePoint Online.

As for your connection to Office 365 itself, well, although there’s a Connect-MsolService cmdlet there’s no corresponding Disconnect-MsolService cmdlet. So, in that case, you will just have to close the Windows PowerShell window. Nevertheless, it’s still a good idea to properly disconnect from SharePoint, Lync, and Exchange.

 
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft