【问题标题】:Detecting csv files in newly sub-folder in PowerShell在 PowerShell 中检测新子文件夹中的 csv 文件
【发布时间】:2014-12-06 10:09:50
【问题描述】:

我有一个名为 C:\2014-15 的文件夹,每个月都会创建新的子文件夹,其中包含 csv 文件,即

  1. C:\2014-15\Month 1\LTC
  2. C:\2014-15\Month 2\LTC
  3. C:\2014-15\Month 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 
}

我得到的错误是:

Register-ObjectEvent : 无法订阅事件。源标识符为“FileCreated”的订阅者已存在。 在行:8 字符:34 + $onCreated = Register-ObjectEvent

【问题讨论】:

  • 到目前为止你得到了什么代码?
  • 嗨。我没有任何可以工作的代码。我使用过 FileSystemWatcher 和 move-item。
  • 脚本运行计划是什么?每天(过夜)?
  • 请解释您尝试了什么以及为什么它不起作用(错误消息?)如果文件夹被移动到其他地方,那么您似乎只要文件夹存在就移动它,因为文件夹应该通常是空的。
  • 发生错误是因为您正在测试,已经运行Register-ObjectEvent。如果您的脚本每月运行一次并创建 /Month x/LTC 目录以及移动日志文件会更容易吗?

标签: powershell powershell-3.0


【解决方案1】:

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 中......

【讨论】:

  • 脚本仅将内容为空的 2014-15 文件夹复制到“N:Test”目标文件夹中。
  • 您需要更改Copy-Item 才能执行您需要的确切命令。如果它们在 LTC 文件夹中,它们是否会在创建文件夹时立即创建?
  • 我将 Copy-Item 更改为: Copy-Item -Path $item -Destination $destination 但这会复制没有 csv 文件的 LTC 文件夹,但我只需要复制 LTC 文件夹中的 csv 文件.
  • 试试Copy-Item -Path "$item\*.csv" -Destination $destination
  • 我使用了 Copy-Item -Path "$item*.csv" 但它只复制了一些文件
猜你喜欢
  • 1970-01-01
  • 2016-11-21
  • 1970-01-01
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多