General question about Powershell try and catch statements

Greetings folks,

I always have to turn to you guys when I have tough questions.

With try and catch statements, can you test multiple statements?

For example, I want to test two statements.

try
 {
       $machine = Get-ADObject "CN=syssec-$servername,OU=servers,OU=NISNetgroups,OU=Applications,DC=company,DC=com"; $machine = Get-ADObject "CN=syssec-$servername,OU=WindowsServers,OU=Groups,DC=company,DC=com"
        }
       
catch {$machine = $null; Write-Host "AD Object syssec-$servername not found"}

When I run this code, it will execute but it won't evaluate the second statement.

Your thoughts?

Thanks,

M

September 10th, 2015 12:18pm

EDIT: My example was bad, see Bill's response below.

Free Windows Admin Tool Kit Click here and download it now
September 10th, 2015 12:26pm

If the first statement fails, then it catches the error.

In that case, of course it won't execute the second statement.

If you want to test two independent statements, you will need to use two try/catch statements.

September 10th, 2015 12:27pm

Oh ok.  That's what I thought. 

Thanks folks!

Free Windows Admin Tool Kit Click here and download it now
September 10th, 2015 12:40pm

Is this what you need? 

try {
  $machine = Get-ADObject "CN=syssec-$servername,OU=servers,OU=NISNetgroups,OU=Applications,DC=company,DC=com"
 } 
catch {
  $machine = $null
 }

if ($machine -eq $null) {
  try {
    $machine = Get-ADObject "CN=syssec-$servername,OU=WindowsServers,OU=Groups,DC=company,DC=com"
   } 
  catch {
    $machine = $null
   }
 }
 
if ($machine -eq $null) {
  Write-Host "AD Object syssec-$servername not found"
 }


September 10th, 2015 5:45pm

Is this what you need? 

try {
  $machine = Get-ADObject "CN=syssec-$servername,OU=servers,OU=NISNetgroups,OU=Applications,DC=company,DC=com"
 } 
catch {
  $machine = $null
 }

if ($machine -eq $null) {
  try {
    $machine = Get-ADObject "CN=syssec-$servername,OU=WindowsServers,OU=Groups,DC=company,DC=com"
   } 
  catch {
    $machine = $null
   }
 }
 
if ($machine -eq $null) {
  Write-Host "AD Object syssec-$servername not found"
 }


  • Edited by LarryWeiss Thursday, September 10, 2015 9:44 PM
Free Windows Admin Tool Kit Click here and download it now
September 10th, 2015 9:43pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics