why is funcmail erroring out??

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of tommls tommls 3 years, 6 months ago.

  • Author
    Posts
  • #11003
    Profile photo of tommls
    tommls
    Participant

    I have this script to check if a folder exists and alert me if it does not:

    $path = "D:\foo\EEE\"
    if(!(Test-Path -Path $path))
      {
       # folder does not exist
       FuncMail -To "tlyczko@mountainlakeservices.org" -From "administrator@mountainlakeservices.org"  -Subject "fp1: folder deleted" -Body "fp1: folder EEE deleted" -smtpServer "172.16.0.19"
      }
    else
      {
       # folder exists 
       Write-Host –NoNewLine "Counting from 1 to 8 (in seconds):  "
       cls
       exit
      }
      
    function FuncMail {
        param($To, $From, $Subject, $Body, $smtpServer)
        $msg = new-object Net.Mail.MailMessage
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $msg.From = $From
        $msg.To.Add($To)
        $msg.Subject = $Subject
        $msg.IsBodyHtml = 1
        $msg.Body = $Body
        $smtp.Send($msg)
    }
    

    I call the script like so within a .bat file:
    10:28 AM 10/23/2013

    rem check folder existence
    rem if not exist, send email
    powershell -command C:\scripts\testFolder.ps1
    pause

    testing from PowerShell ISE per se, the script works...!!
    testing from the .bat file, it does not, with this error shown in the attached image:

    FuncMail is not recognized...

    How do I make the script work properly??

    Thank you, Tom

  • #11005
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    In PowerShell scripts, function definitions have to come before calls to those functions in the script. You could place the FuncMail definition at the beginning of the script:

    function FuncMail {
        param($To, $From, $Subject, $Body, $smtpServer)
        $msg = new-object Net.Mail.MailMessage
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $msg.From = $From
        $msg.To.Add($To)
        $msg.Subject = $Subject
        $msg.IsBodyHtml = 1
        $msg.Body = $Body
        $smtp.Send($msg)
    }
    
    $path = "D:\foo\EEE\"
    if(!(Test-Path -Path $path))
      {
       # folder does not exist
       FuncMail -To "tlyczko@mountainlakeservices.org" -From "administrator@mountainlakeservices.org"  -Subject "fp1: folder deleted" -Body "fp1: folder EEE deleted" -smtpServer "172.16.0.19"
      }
    else
      {
       # folder exists 
       Write-Host –NoNewLine "Counting from 1 to 8 (in seconds):  "
       cls
       exit
      }
    

    Or you could just use the Send-MailMessage cmdlet, which does the same thing.

  • #11006
    Profile photo of tommls
    tommls
    Participant

    OIC — it doesn't come first in another script where it's used.
    That did the trick...!! 🙂 🙂
    Thank you for such a quick reply!! 🙂 tom

You must be logged in to reply to this topic.