【发布时间】:2022-03-22 06:29:24
【问题描述】:
希望这对 powershell 专家来说是一个快速的答案。
我有一个使用 IO.FileSystemWatcher 的 powershell 脚本。当我在 ISE 中测试我的代码而不保存文件时,文件观察器工作。但是当脚本保存在另一个位置时,它不会执行(即使在 ISE 中)。
我假设有一些执行策略阻止它。我需要做什么才能让它工作?我是管理员,我需要它在服务器上运行时才能运行。
try
{
Write-Warning "FileSystemWatcher is monitoring $Path"
# create a filesystemwatcher object
$watcher = New-Object -TypeName IO.FileSystemWatcher -ArgumentList $Path, $FileFilter -Property @{
IncludeSubdirectories = $IncludeSubfolders
NotifyFilter = $AttributeFilter
}
# start monitoring manually in a loop:
do
{
# wait for changes for the specified timeout
# IMPORTANT: while the watcher is active, PowerShell cannot be stopped
# so it is recommended to use a timeout of 1000ms and repeat the
# monitoring in a loop. This way, you have the chance to abort the
# script every second.
$result = $watcher.WaitForChanged($ChangeTypes, $Timeout)
# if there was a timeout, continue monitoring:
if ($result.TimedOut) { continue }
if ($RunVersion -eq "Live")
{
ProcessCsv -Change $result
}else
{
ProcessCsvTest -Change $result
}
# the loop runs forever until you hit CTRL+C
} while ($true)
}
catch
{
write-host "An error occurred"
Write-Host $_.ScriptStackTrace
}
finally
{
# release the watcher and free its memory:
$watcher.Dispose()
Write-Warning 'FileSystemWatcher removed.'
}
【问题讨论】:
-
你怎么知道它不起作用?有错误吗?您是否尝试过捕获和写出错误?请注意,如果您不包含此信息,“它不起作用”几乎无法提供帮助。
-
我认为您需要将
enableraisingevents设置为$True。 -
@iRon,当使用同步
.WaitForChanged()方法时,实际上不需要。 -
@Colyn1337 脚本运行了,但是当文件保存在我的机器上时,filesystemwatcher 片段不会执行。但它在粘贴到新的未保存的 ISE 文件并运行它时确实有效。我在测试时使用了不受限制的 Set-ExecutionPolicy 本地执行策略,但它不起作用。我感觉有一些全球政策阻止了这一点 - 几个小时后,它在没有任何代码更改的情况下工作。
标签: powershell