Detecting csv files in newly sub-folder in PowerShell -
i have folder called c:\2014-15 , new sub folders created every month contain csv files i.e
- c:\2014-15\month 1\ltc
- c:\2014-15\month 2\ltc
- c:\2014-15\month 3\ltc
how write script detect when ltc sub folder created every month , move csv files 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 is:
register-objectevent : cannot subscribe event. subscriber source identifier 'filecreated' exists. @ 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
notify on different event: [io.notifyfilters]'directoryname'
. removes need $filter
since filename events not relevant.
you should notify renamed folders and created folders, making final script 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") { # stuff: copy-item -path $folder -destination $destination } } $renamed = register-objectevent $fsw -eventname renamed -action { $item = get-item $eventargs.fullpath if ($item.name -ilike "ltc") { # stuff: copy-item -path $folder -destination $destination } }
from same console can unregister since console knows $created
, $renamed
:
unregister-event $created.id unregister-event $renamed.id
otherwise need use bit uglier:
unregister-event -sourceidentifier created -force unregister-event -sourceidentifier renamed -force
also, question. didn't realise these event captures existed in powershell until now...
Comments
Post a Comment