gpt4 book ai didi

powershell - FileSystemWatcher 在 PowerShell ISE 中工作,但在运行时不工作

转载 作者:行者123 更新时间:2023-12-04 00:06:11 24 4
gpt4 key购买 nike

我想监控文件夹并移动符合特定条件的文件,所以我尝试使用 FileSystemWatcher。

我有一个函数,每个新文件都会被调用:

function ProcessFile()
{
param ([string]$filename)
Write-Host "Processing file '$filename' to $destination"
}

然后我设置了一个 FSW:

Write-Host "Watching $source for new files..."
$fsw = New-Object IO.FileSystemWatcher $source, $filter -Property @{IncludeSubdirectories = $false; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action
{
ProcessFile $Event.SourceEventArgs.FullPath
}

当我从 ISE 运行它时,它工作正常,并且我放入监视文件夹的任何文件都被正确跟踪,但如果我启动 PowerShell 窗口并使用 .\FileWatch.ps1 运行脚本,则什么也不会发生。

我看到“正在观看...”消息,但从未看到“正在处理...”消息

这是在 ISE 中工作但在 shell 中不工作的完整脚本...

$source = 'D:\Dev\PowerShell\FileWatch\Test\Source'
$filter = '*.*'
$destination = 'D:\Dev\PowerShell\FileWatch\Test\Found\'

function ProcessFile()
{
param ([string]$filename)
Write-Host "Processing file '$filename' to $destination"
}

Write-Host "Watching $source for new files..."
$fsw = New-Object IO.FileSystemWatcher $source, $filter -Property @{IncludeSubdirectories = $false; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
ProcessFile $Event.SourceEventArgs.FullPath
}

最佳答案

问题是您的函数 ProcessFile 没有加载到 powershell session 中。

尝试以这种方式加载脚本:

. .\myscript.ps1

这样你的代码在我的系统中就可以工作了!

了解 Dot Sourcing powershell 中的脚本。

关于powershell - FileSystemWatcher 在 PowerShell ISE 中工作,但在运行时不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12860169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com