locked
a question on error handling RRS feed

  • Question

  • i'm trying my first time to handle errors. from googling around, i found and come up with the following script. however, what i don't get is why it says the Try statement doesn't have its Catch or Finally block.

    $ErrorActionPreference = 'Continue'
    
    Import-CSV 'd:\dept.csv' | foreach-object {
      try {
        if (Get-ADuser $_.ID -SearchBase "OU=Main,DC=ACME,DC=COM" 2>error.txt ) {
          Set-ADuser -Identity $_.ID -Replace @{physicalDeliveryOfficeName=" "}
        }
      catch {
        
      }
      }
    }
    all i want is to output the error to some text file and to continue with the loop without showing an error on screen.


    Thursday, October 6, 2016 8:13 AM

Answers

  • Hi Reno,

    this is due to your catch block being within your try block, not afterwards. Try this:

    Import-CSV 'd:\dept.csv' | foreach-object {
    	try
    	{
    		if (Get-ADuser $_.ID -SearchBase "OU=Main,DC=ACME,DC=COM" 2>error.txt)
    		{
    			Set-ADuser -Identity $_.ID -Replace @{ physicalDeliveryOfficeName = " " }
    		}
    	}
    	catch
    	{
    		
    	}
    }

    Cheers,
    Fred


    There's no place like 127.0.0.1

    • Marked as answer by Reno Mardo Thursday, October 6, 2016 8:25 AM
    Thursday, October 6, 2016 8:18 AM

All replies

  • Hi Reno,

    this is due to your catch block being within your try block, not afterwards. Try this:

    Import-CSV 'd:\dept.csv' | foreach-object {
    	try
    	{
    		if (Get-ADuser $_.ID -SearchBase "OU=Main,DC=ACME,DC=COM" 2>error.txt)
    		{
    			Set-ADuser -Identity $_.ID -Replace @{ physicalDeliveryOfficeName = " " }
    		}
    	}
    	catch
    	{
    		
    	}
    }

    Cheers,
    Fred


    There's no place like 127.0.0.1

    • Marked as answer by Reno Mardo Thursday, October 6, 2016 8:25 AM
    Thursday, October 6, 2016 8:18 AM
  • oh. didn't catch that one :)

    thanks!

    Thursday, October 6, 2016 8:25 AM