Windows 脚本侦听文件夹事件Powershell

Windows 脚本侦听文件夹事件Powershell,windows,powershell,exe,Windows,Powershell,Exe,我对Powershell脚本有问题。我在以下代码行中所做的工作有望通过步骤1-4得到明确: # STEP (1) Create listener on folder where outputfile.pdf file will be created # (folder here is `$folder`). # STEP (2) Wait for new .pdf file to be created. # STEP (3) When file is created, se

我对Powershell脚本有问题。我在以下代码行中所做的工作有望通过步骤1-4得到明确:

# STEP (1) Create listener on folder where outputfile.pdf file will be created 
#         (folder here is `$folder`).

# STEP (2) Wait for new .pdf file to be created.

# STEP (3) When file is created, send mail and print.

# STEP (4) Unsubscribe listener.


$folder = 'X:\foldername'
$filter = '*.*'                             # <-- set this according to your requirements

# STEP (1)

$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
 IncludeSubdirectories = $false             # <-- set this according to your requirements
 NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}

# Run python script, removing existing .pdf-files.
Write-Host "Running PS-script..."
start-process runrisk.bat -workingdirectory "H:\FX\"

# STEP (2)

$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
 $path = $Event.SourceEventArgs.FullPath
 $name = $Event.SourceEventArgs.Name
 $changeType = $Event.SourceEventArgs.ChangeType
 $timeStamp = $Event.TimeGenerated

 # STEP (3)    

 # Call sendMail.ps1 to send mail confirmation
 invoke-expression -Command .\sendMail.ps1
 Write-Host "The file '$name' was $changeType at $timeStamp `r"

 # Print file
 start-process outputfile.pdf -workingdirectory "X:\folder1" -verb Print

 # STEP (4)
 # unregister current subscription
  Unregister-Event -SourceIdentifier FileCreated

}
我已经围绕这个脚本构建了一个.exe文件。如果我直接从PowerShell运行这个.ps1文件,一切都会按预期运行:1在文件夹中创建侦听器,2删除旧的.pdf文件并等待创建新的.pdf文件,3在创建事件时打印并发送邮件,4取消订阅侦听器

当尝试运行.exe文件时,或例如通过Windows任务计划程序运行ps1文件时,它似乎只运行到步骤2,即,似乎没有创建侦听器,因此在bat文件创建.pdf文件完成时不会发生任何事情。它只是闪烁一些命令窗口,就是这样

任何想法都将非常感激

谢谢,
Niklas

您的脚本执行Register objectEvent,然后立即停止。因此,如果将触发任何事件,您不允许脚本等待足够长的时间来查看与该触发器关联的任何操作。留出足够时间的一种方法是在脚本末尾添加一行,如下所示:

while ($true) {sleep 5}
上面这一行允许脚本等待任何触发器发生和操作发生。请参见上的示例

在交互式PowerShell窗口中执行脚本时,注册事件侦听器会在脚本终止后持续存在,但前提是保持窗口打开。也许这会让你看到行动的发生。但是,一旦关闭窗口,eventlistener将自动取消注册,并且不会采取任何操作


我不知道创建可执行文件是如何改变这种行为的,但据我所知,您创建的可执行文件也会立即终止,不会等待事件触发,这不是从脚本中获得任何结果的正确行为。

提示1:使用完整路径。\sendMail.ps1应为c:\scripts\sendMail.ps1或任何您的路径。提示2:以运行ask的用户的身份打开命令提示符,并从任务(即powershell.exe c:\scripts\myscript.ps1)中执行确切的命令,然后查看出现了什么情况。您的驱动器X:或H:安装不正确是有道理的-或者这可能是许多其他问题..谢谢@Raf。但当我在cmd或powershell中显式运行此脚本时,它就像时钟一样工作。但是,在执行此操作时,我实际打开了一个窗口,而当我按原样(即通过exe)运行脚本时,它会关闭cmd-window。启动脚本时使用的命令是什么?将-noexit开关添加到powershell,cmd窗口将保持不变。另外,您不需要.exe就可以将代码作为任务运行,您只需将其计划为执行powershell-noexit C:\scripts\myscript.ps1,但如果需要.exe文件怎么办。我可以使用PowerGUI编译为.exe,但即使如此,当到达第2步时,打开的窗口也会自动关闭,即当它应该打开一个新的cmd窗口时,等等。。。