Cyl*_*ric 3 powershell filesystemwatcher
我想监视一个文件夹并移动符合特定条件的文件,所以我正在尝试使用FileSystemWatcher.
我有一个将与每个新文件调用的函数:
function ProcessFile()
{
param ([string]$filename)
Write-Host "Processing file '$filename' to $destination"
}
Run Code Online (Sandbox Code Playgroud)
然后我建立了一个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
}
Run Code Online (Sandbox Code Playgroud)
当我从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
}
Run Code Online (Sandbox Code Playgroud)
问题是您的功能ProcessFile未在powershell会话中加载.
尝试以这种方式加载脚本:
. .\myscript.ps1
Run Code Online (Sandbox Code Playgroud)
这样你的系统中的代码就可以了!
阅读Dot SourcingPowerShell中的脚本.
| 归档时间: |
|
| 查看次数: |
3166 次 |
| 最近记录: |