2014-12-06 50 views
0

我有一個文件夾名爲C:\ 2014-15和新的子文件夾中創建每月包含CSV文件,即檢測CSV文件中新的子文件夾中的PowerShell

  1. C:\ 2014-15 \ 1個月\ LTC
  2. C:\ 2014-15 \月2 \ LTC
  3. C:\ 2014-15 \月3 \ LTC

如何編寫一個腳本這將檢測何時LTC子文件夾是爲每個月創建的,並將csv文件移動到N:\ Test?

更新:

$folder = 'C:\2014-15' 
$filter = '*.*' 
$destination = 'N:Test\' 
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{ 
IncludeSubdirectories = $true 
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite' 
} 
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { 
$path = $Event.SourceEventArgs.FullPath 
$name = $Event.SourceEventArgs.Name 
$changeType = $Event.SourceEventArgs.ChangeType 
$timeStamp = $Event.TimeGenerated 
Write-Host 
Copy-Item -Path $path -Destination $destination 
} 

我得到的錯誤是:

註冊-ObjectEvent:無法訂閱事件。源標識符爲'FileCreated'的用戶已經存在。 在行:8字符:34 + $ onCreated =註冊-ObjectEvent < < < < $ FSW創建-SourceIdentifier FileCreated -Action { + CategoryInfo:InvalidArgument:(System.IO.FileSystemWatcher:FileSystemWatcher的)[註冊-ObjectEvent] ArgumentException的 + FullyQualifiedErrorId:SUBSCRIBER_EXISTS,Microsoft.PowerShell.Commands.RegisterObjectEventCommand

+0

你到目前爲止得到了什麼代碼? – xXhRQ8sD2L7Z 2014-12-06 12:55:27

+0

嗨。我沒有任何代碼可以工作。我已經使用FileSystemWatcher和move-item。 – Djbril 2014-12-07 21:31:07

+0

什麼是腳本運行計劃?每日(過夜)? – Neolisk 2014-12-07 21:39:40

回答

0

Credit to this post.

通知對不同的事件:[IO.NotifyFilters]'DirectoryName'。由於文件名事件不相關,這消除了對$filter的需要。

你也應該通知的重命名的文件夾創建的文件夾,使您最終的腳本是這樣的

$folder = 'C:\2014-15' 
$destination = 'N:\Test' 

$fsw = New-Object System.IO.FileSystemWatcher $folder -Property @{ 
    IncludeSubdirectories = $true 
    NotifyFilter = [IO.NotifyFilters]'DirectoryName' 
} 

$created = Register-ObjectEvent $fsw -EventName Created -Action { 
    $item = Get-Item $eventArgs.FullPath 
    If ($item.Name -ilike "LTC") { 
     # do stuff: 
     Copy-Item -Path $folder -Destination $destination 
    } 
} 

$renamed = Register-ObjectEvent $fsw -EventName Renamed -Action { 
    $item = Get-Item $eventArgs.FullPath 
    If ($item.Name -ilike "LTC") { 
     # do stuff: 
     Copy-Item -Path $folder -Destination $destination 
    } 
} 

從您可以註銷,因爲該控制檯知道$created$renamed同一控制檯:

Unregister-Event $created.Id 
Unregister-Event $renamed.Id 

否則你需要使用這個有點醜的:

Unregister-Event -SourceIdentifier Created -Force 
Unregister-Event -SourceIdentifier Renamed -Force 

此外,謝謝你的問題。我沒有意識到這些事件捕獲存在於PowerShell中,直到現在...

+0

該腳本僅將具有空白內容的2014-15文件夾複製到'N:Test'目標文件夾中。 – Djbril 2014-12-08 11:44:06

+0

您將需要更改'Copy-Item'來執行您需要的確切命令。如果他們在LTC文件夾中,那麼當文件夾被創建時它們會立即崩潰嗎? – xXhRQ8sD2L7Z 2014-12-08 11:51:54

+0

我將Copy-Item更改爲:Copy-Item -Path $ item -Destination $ destination,但是這會複製沒有csv文件的LTC文件夾,但我需要僅將LTC文件夾中的csv文件複製。 – Djbril 2014-12-08 12:54:55

相關問題