Determine if connect-msolservice has already been successfully called

我只是一个虾纸丫 提交于 2020-02-01 22:13:36

问题


I am writing an Office 365 assistance tool in PowerShell and have what I think is a simple question I can't find the answer to. How can I tell if a connection as created by Connect-MsolService is present and active? There must be some way to know because the other cmdlets can check, I just don't know what that way is and I'm not having luck finding it.


回答1:


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"
}



回答2:


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
}



回答3:


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.




回答4:


All you have to do is get-pssessionand that will let you know if you are connected to msol services based on the configuration name. If you want to automate a connection process you can set up an if else loop to check the configuration name and the state. Let me know if you would like an example of this, I have this set up on a web app I built to query user information on Office 365 and display it on a web page.



来源:https://stackoverflow.com/questions/12977477/determine-if-connect-msolservice-has-already-been-successfully-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!