如何将变量传递到 Powershell ObjectEvent 操作中

问题描述 投票:0回答:1

我正在编写一个工具,每当将新文件写入 Windows 服务器上的文件夹时,该工具就会执行操作。我正在使用以下

$action = {
write-host "action fired"
Process-file $event.SourceEventArgs.FullPath $DestFolder
}    
$onCreated = Register-ObjectEvent $fileSystemWatcher Created -SourceIdentifier FileCreated -Action $Action

我有两个问题。 process-file 命令是几行运行良好的代码的占位符。我的问题是 $Destfolder 变量。这是一个全局变量,在我分配 $Action 时存在,但在事件触发时不存在。我知道我需要强制评估变量或以某种方式创建委托,但我不知道如何做到这一点。我可能没有在寻找正确的名字。

第二个是,在当前状态下,我的脚本运行并退出,然后事件开始触发。这在命令行中工作得很好,但是如果它作为后台任务运行,我应该如何执行此操作。我不知道应该如何保持我的脚本“开放”。 我尝试在脚本末尾添加睡眠,但这阻止了事件的触发,因此循环睡眠不起作用。 我可能再次寻找了错误的东西,并且有一个很好的技术可以做到这一点。我所需要的只是指向正确的方向。

powershell events filesystemwatcher
1个回答
0
投票
  • 使用

    Register-ObjectEvent
    -MessageData
    参数将数据从调用者传递到
    -Action
    脚本块。

    # Declare your script block with a parameter that will be passed
    # via Register-ObjectEvent -MessageData 
    $action = {
      param($DestFolder}
      write-host "action fired"
      Process-file $event.SourceEventArgs.FullPath $DestFolder
    }    
    
    # Pass the value of the local $destFolder variable via -MessageData
    $onCreated = Register-ObjectEvent -MessageData $destFolder $fileSystemWatcher Created -SourceIdentifier FileCreated -Action $Action
    
  • 保持脚本处于活动状态,以便无限期地继续处理事件,并在终止时清理

    Register-ObjectEvent
    返回的事件作业。

    try {
      # Indefinitely wait for events to arrive.
      # Note: With this approach, the script must be terminated
      #       with Ctrl-C, or the hosting PowerShell process must be terminated
      Wait-Event -SourceIdentifier FileCreated
    } 
    finally {
      # Clean up the event job, which also unregisters the event subscription.
      $onCreated | Remove-Job -Force
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.