我需要持续监视特定的“drop”文件夹中的(小)pdf 文件并自动打印和删除它们。打印本身将由 SumatraPDF 处理(因为我认为没有内置的 Windows 方法)。
在 PowerShell 中创建临时 WMI 事件监视器非常简单:
$WQLquery = "SELECT * FROM __InstanceCreationEvent WITHIN 5 " +
"WHERE TargetInstance ISA 'CIM_DataFile' " +
"AND TargetInstance.Extension = 'pdf' " +
"AND TargetInstance.Drive = '$($Drive):' " +
"AND TargetInstance.Path = '$($Folder.replace('\','\\'))'"
$Action = {
$TimedOut = $null
$PrintProcess = Start-Process -FilePath $Sumatra -ArgumentList "-Print-To $Printer `"$($EventArgs.NewEvent.TargetInstance.Name)`"" -PassThru
$PrintProcess | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue -ErrorVariable TimedOut
if ($TimedOut) {
"Printing $($EventArgs.NewEvent.TargetInstance.Name) timed out." | Out-File $ErrorLogPath -Append
$PrintProcess.kill
} elseif ($PrintProcess.ExitCode -ne 0) {
"Error for $($EventArgs.NewEvent.TargetInstance.Name) : $($PrintProcess.ExitCode)" | Out-File $ErrorLogPath -Append
} else {
Remove-Item $EventArgs.NewEvent.TargetInstance.Name -Force
}
}
Register-CimIndicationEvent -Query $wqlquery -SourceIdentifier 'FileCreated' -Action $Action
因为它使用脚本块,所以直到每个事件后调用
$Action
才会处理引用事件的变量。
对于具有字符串属性而不是脚本块的永久事件监视器,如何在使用者中使用事件属性?
我希望使用
CommandLineEventConsumer
调用 PowerShell 脚本,并向其传递触发事件的文件名。例如:
$FilterArgs = @{
ClassName = '__EventFilter'
NameSpace = 'root\subscription'
ErrorAction = 'Stop'
Property = @{
Name = 'PDFCreatedFilter'
EventNamespace = 'root\CIMV2'
QueryLanguage = 'WQL'
Query = $WQLQuery
}
}
$FilterInstance = New-CimInstance @FilterArgs
$ConsumerArgs = @{
ClassName = 'CommandLineEventConsumer'
NameSpace = 'root\subscription'
ErrorAction = 'Stop'
KillTimeout = 10
Property = @{
Name = 'FileCreatedConsumer'
EventNamespace = 'root\CIMV2'
ExecutablePath = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe'
CommandLineTemplate = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe ' +
'-ExecutionPolicy bypass -NoProfile -file "$MyScriptPath" ' +
"-Name `"$($EventArgs.NewEvent.TargetInstance.Name)`" -Printer $MyPrinterName"
}
}
$ConsumerInstance = New-CimInstance @ConsumerArgs
但是,在我创建消费者时不会定义
$EventArgs.NewEvent.TargetInstance.Name
。
如果使用
ActiveScriptEventConsumer
参数的 ScriptText
是执行此操作的唯一方法,我可能会偶然发现 VBscript,但我仍然需要语法才能使其工作。
谢谢。
我也有同样的问题。传递给 CommandLineTemplate 的变量似乎字符串太复杂。