繁体   English   中英

powershell,如何管理目录并将文件移动到另一个文件夹

[英]powershell, how to mointor a directory and move files over to another folder

我正在使用Powershell3。需要监视一个文件夹,如果有任何图像文件,请将它们移到另一个文件夹中。

这是我的代码,我对其进行了测试,它无法正常工作,无法找出需要解决的问题。

#<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:\
}

您尚未注册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
}

事件操作脚本在只能访问全局变量的单独范围内运行,因此,根据您的实现,在尝试在操作脚本中使用这些变量时会遇到问题。 一种无需诉诸声明全局变量的方法(坏的mojo!)是使用可扩展字符串创建一个脚本块,并在注册事件之前将变量扩展:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM