![](/img/trans.png)
[英]Copy files in a folder structure to their respective sub-folder with Powershell
[英]Detecting csv files in newly sub-folder in PowerShell
我有一个名为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创建-SourceIdentifier FileCreated -Action {+ CategoryInfo:InvalidArgument:(System.IO.FileSystemWatcher:FileSystemWatcher)[Register-ObjectEvent],ArgumentException + FullyQualifiedErrorId :SUBSCRIBER_EXISTS,Microsoft.PowerShell.Commands.RegisterObjectEventCommand
通知其他事件: [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中...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.