Reputation: 93
I'm trying to write a powershell script that executes the Get-DistributionGroup cmdlet. But I want to make sure I have a vaild Office 365 Connection first, if not create connection. Then run cmdlet.
The problem is I also want to make sure the connection succeeds before trying to run the cmdlet. I've used Determine if connect-msolservice has already been successfully called to get what I have. But it's not working.
Basically what I want to do is:
What I have so far is...
param([string]$GroupName)
$Username = "[email protected]"
<#
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"
}
Upvotes: -1
Views: 569
Reputation: 93
Ok, I've figured out what was going on.
I was mixing powershell session configurations.
It was working as intended. The issue was the cmdlet Get-DistributionGroup is part of the Exchange/office365 online config, and thus was falling to the catch due to the cmdlet not found, not because the session failed to create.
So to fix, I had to do the following:
I also added some writes to the screen (for diagnostics) and additional error checking to make sure the Credentials were supplied.
Here is the final Script:
param([string]$GroupName)
$Username = "[email protected]"
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"}
Upvotes: 1