如何使用Register Objectevent调用powershell脚本



我试图在并行模式下执行powershell。有人建议我创建一个事件,每当文件夹发生更改时就会触发该事件。

例如:如果在一个特定的文件夹中创建了一个名为"test1"的文件夹名称,那么我的powershell脚本test1.ps1应该会被触发。

我试图通过Register Objevent获得这个例子,但我没有得到任何好的线索。

如果你已经实现了这样的东西,你能指导我吗?


更新:

当我在"D:\PparallelEvent\temp"文件夹中创建一个名为test1.ps1的文件时,它应该执行test1.ps1-powershell文件。以下是的代码

 $ScriptLoc="D:My_Scripts"
    $watcher = New-Object System.IO.FileSystemWatcher -Property @{Path = 'D:ParallelEventtemp';Filter = '*.txt';NotifyFilter = [System.IO.NotifyFilters]'FileName,LastWrite'}
    $CreatedAction =
    {
    $FilenamewithoutExtn=$(($event.sourceEventArgs.Name).Split('.')[0])
    Start-Job $ScriptLoc$FilenamewithoutExtn.ps1
    Get-Job -State Running | Wait-Job
    } 
Register-ObjectEvent -InputObject $watcher -EventName Created -SourceIdentifier FileCreated -Action $CreatedAction

我的test1.ps1有以下行

[system.windows.forms.messagebox]::show("Hello, Test1!")

但它似乎仍然没有执行test1.ps1。我没有收到任何信息框。我错过什么了吗?

您没有得到messagebox,因为powershell作业作为后台进程运行,不显示ui。

如果将test1.ps1修改为文件重定向

"test " > C:AnywhereYouWantToRedirectDatatestagain.txt

您将能够看到test1.ps1运行并创建重定向文件(testgain.txt)。

最新更新