Back to Basics: Multiple Statements with Try / Catch


A customer question this week. What would happen if they chained a number of statements in a try statement, i.e. would all statements be run or could it be used to provide a form of conditional logic? Imagine this, they only want statement two to run if statement one runs successfully and they only want statement three to run if both statements one and two ran successfully. Not the way I’d do it, but still worth chatting to them about.

 


try {

	Write-Host "1"
	Write-Ghost "2"
	Write-Host "3"

}
catch {

	$_.exception.message

}

 

What’s going to happen here then? Well, the first Write-Host will run, the Write-Ghost statement will be caught by the catch block and the second Write-Host will not run.

Question answered. Still not the way I’d do it.

Capture175

 

Comments (1)

  1. Too basic -:). Thanks for sharing!

Skip to main content