在下面的代码中,有一个名为“$action”= {...} 的参数。括号内有一些变量($path、$logPath 等)。如何从大括号“{}”之外的参数访问变量?我需要我的一个函数(“RunFunctions”)的结果一段时间循环。或者,如果这是一个愚蠢的问题,请您指出我可以找到有关此 {} 表示法的一些信息的地方吗?谢谢。
try {
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\Testers\ResetOptimisation\tracking"
$watcher.Filter = "user_name*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = { $path = $Event.SourceEventArgs.FullPath
$logPath = "C:\Testers\ResetOptimisation\output\log.txt"
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
Add-content $logPath -value $logline
$terminateFlag = RunFunctions $path $changeType $logPath
}
### DECIDE WHICH EVENTS SHOULD BE WATCHED
Register-ObjectEvent $watcher "Created" -Action $action
Register-ObjectEvent $watcher "Changed" -Action $action
Register-ObjectEvent $watcher "Deleted" -Action $action
Register-ObjectEvent $watcher "Renamed" -Action $action
while ($true) {
Write-Host $teminateFlag
if ($teminateFlag -eq 1) {
Exit
}
Start-Sleep 3
}
}
catch {
Write-Host $_
}
最佳答案
{ ... }
是一个脚本 block (字面意思) - 一段可重用的 PowerShell 代码,您可以按需执行(如函数指针或委托(delegate))其他语言)。
通过将存储在变量 $action
中的这样的 block 传递给 Register-ObjectEvent -Action
,只要感兴趣的事件触发,PowerShell 就会调用它,并在一个动态模块,其范围与调用者的范围完全分开。
因此,您的调用代码看不到 block 内创建的变量,因为它们是该 block 的本地变量。
有关 PowerShell 中作用域的更多信息,请参阅 this answer 的底部部分.
虽然 PowerShell通常也允许您在其他范围内创建和修改变量,但如果您采取明确的操作,这不是一个选项使用Register-ObjectEvent -Action
,因为动态模块的作用域从根本上来说无法访问调用者的作用域,只能访问全局作用域。
# !! This works, but is ill-advised.
$global:terminateFlag = RunFunctions $path $changeType $logPath
但是,最好避免使用全局作用域,因为全局变量甚至在脚本退出后仍然存在(它们是 session -全局的)。
更好的解决方案是:
使操作脚本 block 输出调用者的值。
让调用者使用事件作业通过
Receive-Job
接收输出
Register-ObjectEvent -Action
返回。
这是一个演示该技术的简化的独立示例:
它设置一个观察程序,附加一个事件处理程序,并创建一个触发观察程序事件的文件。
try {
# Specify the target folder: the system's temp folder in this example.
$dir = (Get-Item -EA Ignore temp:).FullName; if (-not $dir) { $dir = $env:TEMP }
# Create and initialize the watcher.
$watcher = [System.IO.FileSystemWatcher] @{
Filter = '*.tmp'
Path = $dir
}
# Define the action script block (event handler).
$action = {
# Print the event data to the host.
Write-Host "Event raised:`n$($EventArgs | Format-List | Out-String)"
$terminateFlag = $true
# *Return* a value that indicates whether watching should be stopped.
# This value is later retrieved via Receive-Job.
return $terminateFlag
}
# Subscribe to the watcher's Created events, which returns an event job.
# This indefinitely running job receives the output from the -Action script
# block whenever the latter is called after an event fires.
$eventJob = Register-ObjectEvent $watcher Created -Action $action
# Start watching:
# Note: Not strictly necessary, because, curiously,
# Register-ObjectEvent has aleady done this for us.
$watcher.EnableRaisingEvents = $true
# Using an aux. background job, create a sample file that will trigger the
# watcher, after a delay.
$tempFile = Join-Path $dir "$PID.tmp"
$auxJob = Start-Job { Start-Sleep 3; 'hi' > $using:tempFile }
Write-Host "Watching $dir for creation of $($watcher.Filter) files..."
# Wait in a loop until the action block is run in response to an event and
# produces $true as output to signal the intent to terminate, via Receive-Job.
while ($true -ne (Receive-Job $eventJob)) {
write-host . -NoNewline
Start-Sleep -Milliseconds 500 # sleep a little
}
}
finally {
# Clean up.
# Dispose of the watcher.
$watcher.Dispose()
# Remove the event job (and with it the event subscription).
$eventJob | Remove-Job -Force
# Clean up the helper job.
Remove-Job -ea Ignore -Force $auxJob
# Remove the temp. file
Remove-Item -ea Ignore $tempFile
}
关于电源外壳。无法从 {} 获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59772320/