2014-12-06 99 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

相关问题