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:
- Check for connection
- If connection valid, run command.
- If not Valid, attempt to connect.
- If connection Fails, abort.
- else run command
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"
}