Reputation: 895
I have a folder called C:\2014-15 and new sub folders are created every month which contain csv files i.e
How to write a script which would detect when a LTC sub folder is created for every month and move the csv files to N:\Test?
UPDATED:
$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
}
The error I get is:
Register-ObjectEvent : Cannot subscribe to event. A subscriber with source identifier 'FileCreated' already exists. At line:8 char:34 + $onCreated = Register-ObjectEvent <<<< $fsw Created -SourceIdentifier FileCreated -Action { + CategoryInfo : InvalidArgument: (System.IO.FileSystemWatcher:FileSystemWatcher) [Register-ObjectEvent], ArgumentException + FullyQualifiedErrorId : SUBSCRIBER_EXISTS,Microsoft.PowerShell.Commands.RegisterObjectEventCommand
Upvotes: 0
Views: 478
Reputation: 1716
Notify on a different event: [IO.NotifyFilters]'DirectoryName'
. This removes the need for $filter
since filename events are not relevant.
You should also notify for renamed folders and created folders, making your final script something like this
$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
}
}
From the same console you can unregister since that console knows about $created
and $renamed
:
Unregister-Event $created.Id
Unregister-Event $renamed.Id
Otherwise you need to use this which is bit uglier:
Unregister-Event -SourceIdentifier Created -Force
Unregister-Event -SourceIdentifier Renamed -Force
Also, thanks for the question. I didn't realise these event captures existed in powershell until now...
Upvotes: 0