簡體   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