why is funcmail erroring out??

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

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.

OIC – it doesn’t come first in another script where it’s used.
That did the trick…!! :slight_smile: :slight_smile:
Thank you for such a quick reply!! :slight_smile: tom