Determine if connect-msolservice has already been successfully called

I know this is an old question, but this is how I did this:

# Only run if not already connected
if(-not (Get-MsolDomain -ErrorAction SilentlyContinue))
{
    $O365Cred = Get-Credential -Message "Please provide credentials for Microsoft Online"

    $O365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365Cred -Authentication Basic -AllowRedirection -ErrorAction Stop
    Connect-MsolService –Credential $O365Cred

    Import-PSSession $O365Session | Out-Null
}

If the Connect-MsolService line comes before the $O365Session = line, then inputting incorrect credentials will lead to a false positive on your next run (it will think you're connected, even though you're not because the credentials were wrong.) Doing it this way prevents that little hiccup from happening.

Also notice the -ErrorAction Stop at the end of the $O365Session = New-PSSession line. This prevents it from attempting the Connect-MsolService line with incorrect credentials.


This was my solution.

try
{
    Get-MsolDomain -ErrorAction Stop > $null
}
catch 
{
    if ($cred -eq $null) {$cred = Get-Credential $O365Adminuser}
    Write-Output "Connecting to Office 365..."
    Connect-MsolService -Credential $cred
}

Connect-MsolService return an object once connected, and as far as I can see doesn't add new variables. Maybe you can determine that by running one of the module commands and base it on the execution result of the command:

Get-MsolDomain -ErrorAction SilentlyContinue

if($?)
{
    "connected"
}
else
{
    "disconnected"
}