![](/img/trans.png)
[英]Make a Powershell respond to Register-ObjectEvent events in script mode
[英]How to use Register-Objectevent to invoke a powershell script?
我試圖以並行模式執行 powershell。 我被建議創建一個事件,只要文件夾發生變化就會觸發。
例如:如果在特定文件夾中創建了名為“test1”的文件夾名稱,則應觸發我的 powershell 腳本 test1.ps1。
我試圖用 Register-Objevent 得到這個例子,但我沒有得到任何好的線索。
如果你已經實現了這樣的事情,你能指導我嗎?
更新:
當我在“D:\\ParallelEvent\\temp”文件夾中創建一個名為 test1.ps1 的文件時,它應該執行 test1.ps1 powershell 文件。 以下是代碼
$ScriptLoc="D:\My_Scripts"
$watcher = New-Object System.IO.FileSystemWatcher -Property @{Path = 'D:\ParallelEvent\temp';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 。 我沒有收到任何消息框。 我錯過了什么嗎?
您沒有收到消息框,因為 powershell 作業作為后台進程運行並且不顯示 ui。
如果將 test1.ps1 修改為文件重定向
"test " > C:\AnywhereYouWantToRedirectData\testagain.txt
您將能夠看到 test1.ps1 運行並創建了重定向文件 (testagain.txt)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.