我有一个名为C:\ 2014-15的文件夹,每个月都会创建包含csv文件的新子文件夹,即
如何编写一个脚本来检测每个月创建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
}
我得到的错误是:
Register-ObjectEvent:无法订阅活动。具有源标识符的用户' FileCreated'已经存在。 在行: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
答案 0 :(得分:0)
通知其他活动:[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中存在这些事件捕获......