ps1在ise中起作用,但在powershell或调度任务中不起作用

时间:2018-10-16 12:08:47

标签: powershell monitoring

我现在有点疯了。我有一个可以在ise中完美工作的ps1,但是当我使用Powershell或在计划任务中执行相同的脚本时,该ps1无法正常工作。我认为它只运行一次,然后关闭窗口。 有人可以帮我吗?

这是我试图在自动任务中使用的脚本:

$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)      
}

1 个答案:

答案 0 :(得分:0)

尝试以最高特权运行任务。 这可能是问题所在。 另一个可能的解决方案可能是: 尝试在日程表中添加参数:“ powershell.exe -noexit c:\ xxxx.ps1”。

图片显示复选框。 Highest Privilegs

此图片显示“参数”字段 Argument Box