如何使用Register-Objectevent调用PowerShell脚本?
我试图以并行模式执行powershell。我被建议创建一个事件,在文件夹发生变化时触发。如何使用Register-Objectevent调用PowerShell脚本?
例如:如果在特定文件夹中创建名为“test1”的文件夹名称,则应触发我的powershell脚本test1.ps1。
我正在试图为Register-Objevent得到这个例子,但我没有得到任何好的线索。
如果你已经实现了这样的一些东西,你能指导我吗?
更新时间:
当我创建了一个名为test1.ps1在文件 “d:\ ParallelEvent \ TEMP” 文件夹,它应该执行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。我没有收到任何消息框。我错过了什么?
回答:
您没有收到messagebox,因为powershell作业是作为后台进程运行的,并且不显示ui。
如果您修改test1.ps1到一个文件重定向
"test " > C:\AnywhereYouWantToRedirectData\testagain.txt
,你将能够看到test1.ps1运行和重定向文件被创建(testagain.txt)。
以上是 如何使用Register-Objectevent调用PowerShell脚本? 的全部内容, 来源链接: utcz.com/qa/261580.html