Search code examples
arrayspowershellemailget-childitem

Powershell Check folders and send e-mail


I have a program which checks two paths for files and if there are any files it sends one mail for one person each. They now need four paths checked and multiple person need a mail for a path. e.g.

  • Path 1 - Mail to x, y and z
  • Path 2 - Mail to a and b
  • Path 3 - Mail to x and a
  • Path 4 - Mail to s, r and w

How can I make it easy and most efficient?

$folders = @()
$folders += "\\server\files\Info\test"
$folders += "\\server\files\Info\test2"

$receiver = @()
$receiver += "person1@test.com"
$receiver += "person2@test.com"

$i = 0

$folders | ForEach-Object { 
  $checkforfiles = $_ 
  $directoryInfo = Get-ChildItem $checkforfiles | Measure-Object
  $directoryInfo.count #Returns the count of all of the objects in the directory

  $Numberone = $directoryInfo.Count

  if ($directoryInfo.count -ge 1){
    send-mailmessage -subject "Subject" -Body "There are $checkforfiles files " -from foldercheck@test.com  -to $receiver[$i] `
    -smtpserver  smtp.ser.com

    $i = $i+1
  }
  else{
    write-host "nothing to process"
  }     
}

Solution

  • You could simply extend the array of folders to test and use a switch to determine which users should get an email.

    Also, I would advise using splatting on cmdlets with a lot of parameters to make for cleaner code.

    # an array of folder paths to test
    $folders = "\\server\files\Info\test", "\\server\files\Info\test2", "\\server\files\Info\test3", "\\server\files\Info\test4"
    
    for ($i = 0; $i -lt $folders.Count; $i++) {
        # get the file (and folder) count inside
        $count = @(Get-ChildItem -Path $folders[$i]).Count
        if ($count -gt 0) {
            # determine who to email
            $to = switch ($i) {
                0 { 'personX@test.com', 'personY@test.com', 'personZ@test.com' ; break }
                1 { 'personA@test.com', 'personB@test.com' ; break }
                2 { 'personX@test.com', 'personA@test.com' ; break }
                3 { 'personS@test.com', 'personR@test.com', 'personW@test.com' }
            }
            # set up a hashtable with parameters for splattting to Send-MailMessage
            $mailParams = @{
                To         = $to
                From       = 'foldercheck@test.com'
                Subject    = "Subject"
                Body       = "There are $count files in folder '$($folders[$i])'"
                SmtpServer = 'smtp.ser.com'
                # add more parameters here if needed
            }
            # send the email
            Send-MailMessage @mailParams
        }
        else {
            Write-Host "Empty folder '$folders[$i]'; Nothing to process"
        }
    }