【问题标题】:FileSystemWatcher not firing events till PowerShell closesFileSystemWatcher 在 PowerShell 关闭之前不会触发事件
【发布时间】:2019-06-04 09:48:19
【问题描述】:

我有一个脚本(如下),它监视 .ps1 脚本所在的文件夹。 创建文件时,它会触发一个 .bat 文件来完成一项工作。

最初它会立即运行并关闭。 所以我加了'''Start-Sleep -s 50'''

它有效,但仅在 PowerShell 窗口关闭时触发 .bat 启动。

(因为我不知道文件夹中出现文件需要多长时间,所以这有点没用。

理想情况下,我可以在创建新文件后立即启动 .bat 文件,然后关闭 PowerShell 窗口

$configFilePath = $PSScriptRoot
$filter = '*.*'

$fsw = New-Object IO.FileSystemWatcher $configFilePath, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
    Out-File -FilePath c:\temp\log\Filelog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"
    Set-Location "$PSScriptRoot"
    Start-Process "$PSScriptRoot\PS_Run.bat"
}

Start-Sleep -s 50

【问题讨论】:

  • docs.microsoft.com/en-us/powershell/module/…: "当订阅的事件被引发时,它会被添加到您会话中的事件队列中。要在事件队列中获取事件,请使用 Get-Event cmdlet。"
  • 谢谢,“Get-Event”会取代“Register-ObjectEvent”吗?
  • 不,它不会取代它。

标签: powershell filesystemwatcher


【解决方案1】:

您可以将 Start-Sleep 替换为:

Wait-Event -SourceIdentifier FileCreated

然后你需要像这样向你的观察者添加一个退出命令:

Start-Process "$PSScriptRoot\PS_Run.bat"
exit
}

由于您无法从文件观察程序中退出控制台,因此您可以这样做:

$configFilePath = $PSScriptRoot
$filter = '*.*'

$fsw = New-Object IO.FileSystemWatcher $configFilePath, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
    Out-File -FilePath c:\temp\log\Filelog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"
    Set-Location "$PSScriptRoot"
    Start-Process "$PSScriptRoot\PS_Run.bat"
}
Wait-Event -SourceIdentifier FileCreated -Timeout 50 # or no of seconds before file shows up.

当作为计划任务运行时,这将在创建新文件后立即执行 bat 文件,并在达到超时时关闭控制台。

【讨论】:

  • 嗨,谢谢。工作到退出,尝试:退出,退出-PSSession,退出-主机进程和关闭...窗口保持打开状态..
  • 你是对的。文件观察者无法关闭控制台。您可以在等待事件上设置 -TimeOut。一旦执行完成并且时间已到,这将退出脚本。
  • 我是 PS 新手。那看起来怎么样?在网上找到了一些东西来添加 -Timeout 但我似乎无法让它保持直到执行完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多