ps1 working well in ISE and not in powershell console or in scheduled task

0

I'm getting a little crazy already. I have a ps1 script that works perfectly in powershell ISE but when I tell it to run directly with powershell or from a scheduled task it runs only once and closes (I have programmed to place the -noexit parameter in the scheduled task). The code is as follows:

$MonitorFolder = "\sharedfolder"
$MonitorStopFile = "monitor.die"
$smtpServer = "xxx"
$smtpFrom = "xxx"
$smtpTo = "xxx"
#$smtpSubject = "Asignacion tarea LDA"
$smtpSubject = "Asignacion tarea LDA $($MonitorFolder)."
$smtpPort = "25"

$mailparam =@{
    To = $smtpTo
    From = $smtpFrom
    Subject = $smtpSubject
    Body = $smtpBody
    SmtpServer = $smtpServer
    Port = $smtpPort
    #Credential = $smtpCred
}

$SourceID = "MonitorFiles"
$IncomingFiles = Get-ChildItem $MonitorFolder

$smtp = New-Object -TypeName "Net.Mail.SmtpClient" -ArgumentList $smtpServer

$watcher = New-Object System.IO.FileSystemWatcher $MonitorFolder
#Files only. Default is files + directory
$watcher.NotifyFilter = [System.IO.NotifyFilters]'FileName,LastWrite'

$newFileSubscription = Register-ObjectEvent -InputObject $watcher -EventName Created -SourceIdentifier NewFileCreated -Action { 
Write-Host "New file named '$($Event.SourceEventArgs.Name)' arrived in $($MonitorFolder)"

$smtpBody += "'n[$(Get-Date -Format HH:mm:ss)]'tNew file named '$($Event.SourceEventArgs.Name)' arrived in $($MonitorFolder)"

if($Event.SourceEventArgs.Name -eq $MonitorStopFile) {
    Write-Host "Monitoring stopped"
    #Stop monitoring
    Unregister-Event -SubscriptionId $newFileSubscription.Id
    #Dispose FileSystemWatcher
    $watcher.Dispose()
}
$smtp.Send($smtpFrom, $smtpTo, $smtpSubject, $smtpBody)      
}

I would greatly appreciate the help:)

    
asked by Carlos Zurera Andrés 17.10.2018 в 09:48
source

0 answers