【发布时间】:2016-08-10 07:23:44
【问题描述】:
所以我有一个为以下目的设置的脚本:
- 如果文件出现在文件夹中,只需将其移动到该子文件夹上方的文件夹中。 *例如:从 c:\My_Documents\a > c:\My_Documents* 移动
- 每次发生上述情况时,文件名和尝试次数都会存储在哈希表中。一旦相同的文件出现 3 次,该文件就会移动到与结构完全不同的文件夹中,并且会向相应的收款人发送一封电子邮件。 *例如:c:\My_Documents\a > c:\FailedFolder\ *
- 然后删除哈希表中文件的记录。此外,每 10 分钟清除一次整个哈希表。
这可行,我现在的问题是我需要扩展它,以便脚本对以完全相同的方式设置但不重叠的多个文件夹执行此操作。 *例如:c:\My_Documents\a > c:\My_Documents\ && c:\randomFolder\a > c:\randomFolder\ && c:\AnotherRandomFolder\a > c:\AnotherRandomFolder\ *
请有人帮我实现这个目标吗?
请看我当前的代码:
$global:folder = 'C:\Users\random\Documents\IUR Test\r' # Enter the root path you want to monitor.
$global:origin = 'C:\Users\random\Documents\IUR Test'
$filter = '*.*' # You can enter a wildcard filter here.
$global:Failedfolder = 'C:\Users\random\Documents\Failed'
$global:Files = @{}
$timer = New-Object Timers.Timer
$timer.Interval = 600000 # fire every 10 minutes
$timer.AutoReset = $true # Enable the event again after its been fired
$timer.Enabled = $true
# In the following line, you can change 'IncludeSubdirectories to $true if required.
$fsw = New-Object IO.FileSystemWatcher $global:folder, $filter -Property @{IncludeSubdirectories = $false; NotifyFilter = [IO.NotifyFilters]'FileName,LastWrite'}
Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier HashMapClear -Action {
$global:Files.clear()
}
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
ForEach ($file in (gci $global:folder))
{
$fName = $file.Name
if(-not $global:Files.ContainsKey($fName))
{
$global:Files.Add($fName,1)
Move-Item $File.Fullname $global:origin -force
}
Elseif($global:Files.Get_Item($fName) -lt 3)
{
$global:Files.Set_Item($fName,++$global:Files.Get_Item($fName))
Move-Item $File.Fullname $global:origin -force
}
Else
{
$global:Files.Remove($fName)
Move-Item $File.Fullname $global:Failedfolder -force
#### Send error email
}
}
}
# To stop the monitoring, run the following commands:
# Unregister-Event FileCreated
# Unregister-Event HashMapClear
【问题讨论】:
标签: powershell foreach hashtable filesystemwatcher multiple-instances