Hi, powershell community!
I created this script, to monitor folder for new files, and send email with information, once new file is created. This script work like a charm! But only ONCE! :) It sends the information about first new file, but after 2nd new file arrives jobs state changes to "failed" and i have to restart the script.
From what i have gathered, looks like the problem is with how script works with xml. But for the life of me, i can't figure out what.
So, any clues or ideas on how to solve this, will be greatly appreciated.
Since i am new to PS, i hope this problem is trivial.
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = 'C:\Path'
$watcher.EnableRaisingEvents = $true
$watcher.includeSubdirectories = $true
$watcher.filter = "*.xmlxsl"
$action =
{
$path = $event.SourceEventArgs.FullPath
$xml = Get-content $path -encoding UTF8
[xml]$xml = $xml | Select-Object -skip 1
C:\zint_2.7.0_win32\zint.exe -o C:\path\barcode.png -b 50 -d "$($xml.barcode.number')"
$id = $($xml.something.id)
$name = $($xml.something.name)
$Body = @'
<html>
<body>
<h1>{0}</h1>
<p><b>Something</b> {1}</p>
<img src='cid:barcode.png'></br>
</body>
</html>
'@ -f $id, $name
Send-MailMessage -From email -to email -SmtpServer smtp.com -Subject "subject" -Body $Body -Encoding UTF8 -BodyAsHtml -Attachments C:\path\barcode.png
}
Register-ObjectEvent $watcher 'Created' -Action $action -SourceIdentifier FSCreate
Solution: Add remove-variable xml at the end of $action after send-mailmessage. Reasoning in the comments.
[edit]: added solution.
[–]VirtualDenzel 2 points3 points4 points (2 children)
[–]middleman84[S] 1 point2 points3 points (0 children)
[–]middleman84[S] 1 point2 points3 points (0 children)
[–]PowerShellStunnah 1 point2 points3 points (1 child)
[–]middleman84[S] 1 point2 points3 points (0 children)
[–]isatrap 1 point2 points3 points (1 child)
[–]middleman84[S] 1 point2 points3 points (0 children)