Hello!
I have created a script that should sort specific e-mails into different folders. I have an array called $searchwords with all the e-mail adresses and the script works well exept that if for some reason skips the first mail in my mail folder and copies it to the Unknown folder. So for some reason the script goes to the “else” in the first loop… Anyone know why?? If I remove the else code the script run without any problem.
Folder structure:
- Mail (Contains alot of mail files with the file extension .mml)
- WantedMail (Directory that will get all the sorted emails)
- Script.ps1
Here is the code:
$mailfolder = “Mail”
$copiedmail = “WantedMail”
[int]$loop = 1
$searchwords = @(“test@mail.com”,"test1@mail.com")
foreach ($x in (cmd /c dir $mailfolder /b))
{
Write-host $loop -ForegroundColor Yellow
$loop++
foreach ($word in $searchwords)
{
if (Get-Content -Encoding UTF8 $mailfolder\$x -ReadCount 1000 | Where-Object {$_ -match $word})
{
Write-host $word -ForegroundColor green
if(!(Test-Path -Path $copiedmail\$word))
{
New-item -ItemType Directory -Path "$copiedmail\$word"
Copy-item -Path "$mailfolder\$x" "$copiedmail\$word" -Force
}
elseif (Test-Path -Path $copiedmail\$word)
{
Copy-item -Path "$mailfolder\$x" "$copiedmail\$word" -Force
}
}
else
{
if(!(Test-Path -Path "$copiedmail\Unknown"))
{
New-item -ItemType Directory -Path "$copiedmail\Unknown"
Copy-item -Path "$mailfolder\$x" "$copiedmail\Unknown" -Force
}
Write-host "$word was not found in $x" -ForegroundColor Red
}
}
}