none
Try and Catch don't work on powershell module RRS feed

  • Question

  • Hi everyone,

    i'm tring to create a module with a try and catch, but when i call it, the block of expetion doesn't work as i expect, while if i use the code as a function only it works...

    Here the code

    function global:Process{
    param([string]$Process)
    
    ######################################MAIL################################
    function global:SendMail(){
    param([string]$Services)
    $Dest="xxx"
    $smtpServer = "xxx"
    $msg = new-object Net.Mail.MailMessage
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg.From = "xxx"
    $msg.To.Add($Dest)
    $msg.Subject = "Notification about $Services activity"
    $msg.Body = "xxxx"
    $smtp.Send($msg)
    }
    ########################################################################
    
    switch($Process){
        "DSP"{
            if((Get-Service Fax | ForEach-Object {$_.Status}) -eq "Stopped"){
                try
                    {
                        start-service Fax -ea Stop
                    }
                catch
                    {
                        if ( $error[0].Exception -match "Microsoft.PowerShell.Commands.ServiceCommandException")
                            {
                                $error[0].Exception | Out-File C:\log.txt
                                $SendMail $Process
                            }
                    }
               }
            elseif((Get-Service Fax | ForEach-Object {$_.Status}) -eq "Running"){
                Stop-Service Fax}
               }
    
            }
    }
    
    
    Export-ModuleMember -Function Process

    Could you help me? Thanks so much

    Cristian

    Friday, September 19, 2014 3:06 PM

All replies

  • Hi Mugen, 

    Did you resolve this? Notice it is from 2014.


    Thanks, Tim. | Please remember to mark the replies as answers if they help. |

    Thursday, November 24, 2016 10:09 AM