Script behaves differently outside of script editor.
good morning technet,
i’m seeing odd behavior powershell script have written , hoping more experienced can share insights. through magic of copy pasta have developed following script monitor folder new file writes, , send notification email. when run script using script editor (power gui) script runs no errors, , when write folder receive email notifications normally. however, if close script editor, or if run script using powershell executable, not receive notifications @ when files written folder – it’s script not running correctly / not persisting same way when run outside script editor. am missing switch when running script, or there else need consider in terms of how script should behave? any thoughts appreciated. here script:
#unregister-event -sourceidentifier filecreated #<--use if running second time.
$folder = 'e:\temp' #<----set folder path monitored.
$filter = '*.*' #<----can set monitor specific file types.
$fsw = new-object io.filesystemwatcher $folder, $filter -property @{
includesubdirectories = $true #<----can specify whether or not include sub directories.
notifyfilter = [io.notifyfilters]'filename, lastwrite'
}
$oncreated = register-objectevent $fsw created -sourceidentifier filecreated -action {
$path = $event.sourceeventargs.fullpath
$name = $event.sourceeventargs.name
$changetype = $event.sourceeventargs.changetype
$timestamp = $event.timegenerated
write-host "the file '$name' $changetype @ $timestamp"
#create , send email notification.
$today = (get-date -format g)
$smtpserver = “192.168.xxx.xx”
$msg = new-object net.mail.mailmessage
$smtp = new-object net.mail.smtpclient($smtpserver)
$msg.from = "sender@domain.com"
$msg.to.add("recipient@domain.com")
$msg.subject = "notification - new file received"
$msg.body = "a new file has been added folder. the file name is: '$name'. the file recieved @ $today."
$smtp.send($msg)
problem closing powershell session. execute following run dialog (start > run):... if close powershell console stops sending notifications, if close script editor.
powershell -noprofile -noexit -windowstyle hidden e:\fullpathtoscript.ps1 |
Windows Server > Windows PowerShell
Comments
Post a Comment