确定与office365的连接是否可用,如果未连接,则执行某些操作
我正在尝试编写执行Get-DistributionGroup cmdlet的powershell脚本。但我想先确保我有一个可用的Office 365连接,如果没有,请创建连接。然后运行cmdlet 问题是,我还希望在尝试运行cmdlet之前确保连接成功。我曾经得到过我所拥有的。但它不起作用 基本上我想做的是:确定与office365的连接是否可用,如果未连接,则执行某些操作,office365,azure-powershell,Office365,Azure Powershell,我正在尝试编写执行Get-DistributionGroup cmdlet的powershell脚本。但我想先确保我有一个可用的Office 365连接,如果没有,请创建连接。然后运行cmdlet 问题是,我还希望在尝试运行cmdlet之前确保连接成功。我曾经得到过我所拥有的。但它不起作用 基本上我想做的是: 检查连接 如果连接有效,请运行命令 如果无效,请尝试连接 如果连接失败,请中止 else运行命令 到目前为止我所拥有的是 param([string]$GroupName) $Userna
param([string]$GroupName)
$Username = "$GroupName@mydomain.com"
<#
Write-Host "Searching for any Groups that contain '" -NoNewLine
Write-Host "$Username" -NoNewLine -ForegroundColor yellow
Write-Host "'"
#>
try
{
Get-MsolDomain -ErrorAction Stop > $null
}
catch
{
Write-Output "Connecting to Office 365..."
if ($cred -eq $null) {$cred = Get-Credential $O365Adminuser}
Connect-MsolService -Credential $cred
}
try
{
Get-MsolDomain -ErrorAction Stop > $null
Get-DistributionGroup | where { (Get-DistributionGroupMember $_.Name | foreach {$_.PrimarySmtpAddress}) -contains "$Username"}
}
catch
{
throw "Error, connection Failed"
}
param([string]$GroupName)
$Username=”$GroupName@mydomain.com"
尝试
{
获取MSOldDomain-ErrorAction停止>$null
}
抓住
{
写入输出“连接到Office 365…”
如果($cred-eq$null){$cred=Get-Credential$O365Adminuser}
连接MsolService-凭据$cred
}
尝试
{
获取MSOldDomain-ErrorAction停止>$null
Get-DistributionGroup |其中{(Get-DistributionGroup成员$\名称| foreach{$\地址})-包含“$Username”}
}
抓住
{
抛出“错误,连接失败”
}
输出为:
好的,我已经弄清楚发生了什么
- Get-MsolDomain适用于Azure Active Directory
- 从Office365/Exchange Online获取分发组的位置
param([string]$GroupName)
$Username = "$GroupName@mydomain.com"
Write-Host "Searching for any Groups that contain '" -NoNewLine
Write-Host "$Username" -NoNewLine -ForegroundColor yellow
Write-Host "'"
Get-PSSession | Where { $_.ConfigurationName -eq "Microsoft.Exchange" }
if (!(Get-PSSession | Where { $_.ConfigurationName -eq "Microsoft.Exchange" }))
{
Write-Output "Creating Credentials for Office 365..."
if ($UserCredential -eq $null)
{
try
{
$UserCredential = Get-Credential $O365Adminuser
}
catch
{
Write-Host "Credentials not provided, exiting..." -ForegroundColor red -BackgroundColor black
exit
}
}
Write-Output "Creating Session for Office 365..."
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Write-Output "Connecting to Office 365..."
try
{
Import-PSSession $Session -ErrorAction Stop
}
catch
{
throw "Error, connection Failed"
}
}
Write-Output "Seaching Office 365..."
Get-DistributionGroup | where { (Get-DistributionGroupMember $_.Name | foreach {$_.PrimarySmtpAddress}) -contains "$Username"}
在你的脚本开始时,你没有以O365管理员身份登录/验证用户吗?@TylerH我在catch中试图这么做。其想法是您可以多次运行脚本,而不必每次都提供Cred和创建会话。