我正在使用powershell 3.需要监控文件夹,如果有任何图像文件,请将它们移动到antoher文件夹。
这是我的代码,我测试它,它不工作,无法弄清楚需要修复的内容。
#<BEGIN_SCRIPT>#
#<Set Path to be monitored>#
$searchPath = "F:\download\temp"
$torrentFolderPath = "Z:\"
#<Set Watch routine>#
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $searchPath
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true
$created = Register-ObjectEvent $watcher "Created" -Action {
Copy-Item -Path $searchPath -Filter *.jpg -Destination $torrentFolderPath –Recurse
}
#<END_SCRIPT>#
更新
我得到了部分工作。仍然有一个问题。让我们从一个空文件夹开始。我将图像(1.jpg)下载到文件夹,没有移动到Z:驱动器。然后我下载另一个图像(2.jpg)到文件夹。 1.jpg将被移动到Z:驱动器。似乎新创建的人永远不会被移过来。
$folder = "F:\\download\\temp"
$dest = "Z:\\"
$filter = "*.jpg"
$fsw = new-object System.IO.FileSystemWatcher $folder, $filter -Property @{
IncludeSubDirectories=$false
NotifyFilter = [System.IO.NotifyFilters]'FileName, LastWrite'
}
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
Move-Item -Path F:\download\temp\*.jpg Z:\
}
答案 0 :(得分:2)
您尚未注册NotifyFilter。这就是你的代码无效的原因。
这是一个注册NotifyFilter的示例,并打印创建的文件详细信息
$folder = "c:\\temp"
$filter = "*.txt"
$fsw = new-object System.IO.FileSystemWatcher $folder, $filter -Property @{
IncludeSubDirectories=$false
NotifyFilter = [System.IO.NotifyFilters]'FileName, LastWrite'
}
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceVentArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host $path
Write-Host $name
Write-Host $changeType
Write-Host $timeStamp
}
答案 1 :(得分:0)
事件操作脚本在一个只能访问全局变量的单独范围内运行,因此根据您的实现,您在尝试在操作脚本中使用这些变量时会遇到问题。不使用声明全局变量(坏mojo!)的一种方法是使用可扩展字符串来创建一个脚本块,在注册事件之前扩展变量:
$ActionScript =
[Scriptblock]::Create("Copy-Item -Path $searchPath -Filter *.jpg -Destination $torrentFolderPath –Recurse")
$created = Register-ObjectEvent $watcher "Created" -Action $ActionScript