PowerShell如何监控目录并将文件移动到另一个文件夹

3
我是一名使用PowerShell 3的用户。需要监控文件夹,如果有任何图像文件,则将它们移动到另一个文件夹中。
以下是我的代码,我测试过了,但它并没有起作用。我无法确定需要修复哪些问题。
#<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:\
}
2个回答

4

您没有注册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
}

谢谢,我不是很懂,现在部分工作已经完成了,但还需要帮助。请查看我的更新。 - qinking126

0

事件动作脚本在一个单独的范围内运行,只能访问全局变量,因此,根据您的实现方式,尝试在动作脚本中使用这些变量可能会出现问题。绕过而不会使用声明全局变量(坏魔法!)的一种方法是使用可展开字符串来创建一个脚本块,在注册事件之前扩展变量:

$ActionScript = 
 [Scriptblock]::Create("Copy-Item -Path $searchPath -Filter *.jpg -Destination $torrentFolderPath –Recurse")

$created = Register-ObjectEvent $watcher "Created" -Action $ActionScript

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接