none
Errologging with try-catch in module? RRS feed

  • Question

  • Hi,

     

    I have this module which deploys software in SCCM. It consists of serveral functions (New-Application, Create-Collections etc) which are called in 1 main function “Deploy-Software”.

    There is central logging and a mail is sent at the end of the module. I’d now like to add error-logging. So I’d like to add info to this central logging and mail ONLY if something goes wrong.

    To clarify, my module is something like this:

    Function New-Application
    {}

    Function New-Collections
    {}

    …#main function

     Function Deploy-Software

    { New-Application

      New-Collections

    Send-MailMessage –From …

    Add-Content $LogFile  ...

     }

     

    Now the errors I probably would need the try and catch function.Can I put this try catch in my  Deploy-Software function?
    So that would be

     

    Function Deploy-Software

     {

                    Try{

                     New-Application –ErrorAction Stop –errorvariable x

        New-Collections  –ErrorAction Stop –errorvariable x ...

    } catch { $x.ErrorRecord

    $x = $_

     

    $body += $x

    Add-Content $LogFile $x

    }

    Just would like to know that I have the thinking right.


    Please advise.
    J.


    Jan Hoedt

    Monday, October 12, 2015 10:20 AM

Answers

  • You need to study how exception handling works.  It is fairly complex.

    Here is a starter for capturing all trappable errors:

    Function Deploy-Software {	
    	Try {
    		New-Application –ErrorAction Stop 
    		New-Collections –ErrorAction Stop 
    	}
    	catch {
    		Add-Content $LogFile "$_"	
    	}
    }
    

    $_ in the "Catch" is the current error object.


    \_(ツ)_/

    • Marked as answer by janhoedt Friday, October 16, 2015 10:58 AM
    Monday, October 12, 2015 10:57 AM

All replies

  • With Try/Catch you cannot use ErrorVariable.  Just use ErrorAction Stop

    All Commands and exceptions are not trappable. You will have to test well.


    \_(ツ)_/

    Monday, October 12, 2015 10:53 AM
  • You need to study how exception handling works.  It is fairly complex.

    Here is a starter for capturing all trappable errors:

    Function Deploy-Software {	
    	Try {
    		New-Application –ErrorAction Stop 
    		New-Collections –ErrorAction Stop 
    	}
    	catch {
    		Add-Content $LogFile "$_"	
    	}
    }
    

    $_ in the "Catch" is the current error object.


    \_(ツ)_/

    • Marked as answer by janhoedt Friday, October 16, 2015 10:58 AM
    Monday, October 12, 2015 10:57 AM