13

我正在 PowerShell 中编写 Office 365 辅助工具,我认为这是一个我找不到答案的简单问题。如何判断由创建的连接Connect-MsolService是否存在且处于活动状态?必须有某种方法可以知道,因为其他 cmdlet 可以检查,我只是不知道那是什么,而且我没有运气找到它。

4

5 回答 5

5

这是我的解决方案。

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
}
于 2016-02-04T14:29:37.940 回答
4

Connect-MsolService连接后返回一个对象,据我所知,不会添加新变量。也许您可以通过运行其中一个模块命令并根据命令的执行结果来确定:

Get-MsolDomain -ErrorAction SilentlyContinue

if($?)
{
    "connected"
}
else
{
    "disconnected"
}
于 2012-10-19T15:40:39.337 回答
1

我知道这是一个老问题,但这就是我这样做的方式:

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

如果该行位于该Connect-MsolService行之前$O365Session =,则输入不正确的凭据将导致您下次运行时出现误报(它会认为您已连接,即使您不是因为凭据错误。)这样做可以防止这种情况发生发生小问题。

还要注意行-ErrorAction Stop尾的$O365Session = New-PSSession。这可以防止它Connect-MsolService使用不正确的凭据尝试线路。

于 2020-01-23T16:10:53.317 回答
-1

您所要做的就是get-pssession让您知道您是否根据配置名称连接到 msol 服务。如果您想自动化连接过程,您可以设置一个 if else 循环来检查配置名称和状态。如果您想要这样的示例,请告诉我,我在我构建的 Web 应用程序上进行了设置,用于查询 Office 365 上的用户信息并将其显示在网页上。

于 2013-01-12T17:21:17.813 回答
-1

Connect-MsolService将一个模块导入到名为 MSOnline 的 powershell 中,因此只需检查该模块是否存在:

Get-Module -Name MSOnline
于 2020-10-07T21:40:47.513 回答