I am attempting to write a script that will recursively scan a directory, local files with the \'.Error\' extension, then email a group of people with a list of the files. I am
Try breaking the task into simple steps:
$exclusionFilePath = '.\path\to\exclusions\file.txt'
if(-not(Test-Path $exclusionFilePath)){
# Create the exclusion file if it doesn't already exist
New-Item $exclusionFilePath -ItemType File
}
# read list of exclusions from file
$exclusions = Get-Content -Path $exclusionFilePath
# discover files
$array = @((Get-ChildItem -Path \\SERVER\FOLDER -Recurse -Include *.Error).Fullname)
# filter current files against list of exclusions
$array = $array |Where-Object {$exclusions -notcontains $_}
foreach($file in $array){
# send emails
sendEmail
# append new file path to exclusions file
$file |Add-Content -Path $exclusionFilePath
}
Relying on variables from the calling context is a bit of an anti-pattern, I'd strongly suggest refactoring your sendEmail
function to something like:
function Send-ErrorFileEmail {
param(
[string]$File
)
$MailMessageArgs = @{
SMTPServer = "relay.EXAMPLE.com"
From = "Test@EXAMPLE.com"
To = "user@EXAMPLE.com"
Subject = "Error loading XPOLL File - $file"
Body = "This is the body"
}
Send-MailMessage @MailMessageArgs
}
Then use it in the script like:
Send-ErrorFileEmail -File $file