Link to home
Start Free TrialLog in
Avatar of Learner_newBie
Learner_newBie

asked on

Powershell - Add try catch block.

Can some one help me in adding try and catch block to the below code to effectively handle exceptions and write meaningful messages when exception occurs.
$o365module = get-module -name tmp_*
$msolmodule = get-module -name msonline


if( $O365module -eq $null -or $msolmodule -eq $null){
		
	if($O365session -eq $null -or $O365session.State -ne "Opened"){

		$user = "myown@mydomain.onmicrosoft.com"
		$password = Get-content	 "C:\temp\password.txt" | convertto-securestring
	
		$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $user,$password
	
		$O365Session= New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Credentials -Authentication Basic -AllowRedirection -warningaction silentlycontinue

	}

		$temp = Import-PSSession $O365session -allowclobber -WarningAction SilentlyContinue -DisableNameChecking

		$moduleName = $temp.Name

		Import-Module msonline
		Connect-MsolService -Credential $credentials -warningaction silentlycontinue

}
else
{
write-host "$o365Session already exists"
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of n2fc
n2fc
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Learner_newBie
Learner_newBie

ASKER

Hi N2fc,

I am looking to catch all the errors. Yes I am bit concerned about the get-module
Have you tried my suggestion yet? How has that worked for you?
Hi N2FC,

I will try and post you if I get desired result.

Thanks.
Thank you.