【发布时间】:2016-08-05 19:12:07
【问题描述】:
我有一个脚本设置为每次创建文件时为每个循环输入一个。一旦进入循环,它会将文件移动到另一个文件夹,如果必须移动相同的文件 3 次,它将把文件移动到不同的表并从哈希表中删除它的记录。
我的问题是,当我运行脚本时,它不会执行我在 for each 循环中编写的任何操作。只有当我在它上面写脚本时。有人可以请教吗?
$folder = 'C:\Users\jnwankwo\Documents\IUR Test\r' # Enter the root path you want to monitor.
$Failedfolder = 'C:\Users\jnwankwo\Documents\IUR Test\r'
$filter = '*.*' # You can enter a wildcard filter here.
$Files = @{}
$Counter = 1
$folder = 'C:\Users\jnwankwo\Documents\IUR Test\r' # Enter the root path you want to monitor.
$Failedfolder = 'C:\Users\jnwankwo\Documents\IUR Test\r'
$filter = '*.*' # You can enter a wildcard filter here.
$Files = @{}
$Counter = 1
# In the following line, you can change 'IncludeSubdirectories to $true if required.
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
ForEach ($file in $folder)
{
$fName = $file.Name
if (-not $Files.ContainsKey($fName))
{
$Files.Add($fName,$Counter)
}
if (($Files.ContainsKey($fName)) -and ($Files.Item($fName) -lt 3))
{
Move-Item 'C:\Users\jnwankwo\Documents\IUR Test\r\*.txt' 'C:\Users\jnwankwo\Documents\IUR Test' -force
$Files.Set_Item($fName,$Counter++)
}
ElseIf (($Files.ContainsKey($fName)) -and ($Files.Item($fName) -eq 3))
{
$Files.clear()
Move-Item 'C:\Users\jnwankwo\Documents\Failed\' $Failedfolder -force
}
}
}
# To stop the monitoring, run the following commands:
# Unregister-Event FileCreated
【问题讨论】:
-
$file in $folder是什么意思? -
您在脚本块之外声明文件夹变量并且不将其作为参数传递,因此脚本块内的
$folder为空($counter和$Files也是如此)。将它作为参数传递或在脚本块中声明它,也是@AgentK 写的 -
你能发帖告诉我你的意思吗?到目前为止,我没有得到不同的结果。
标签: shell loops powershell foreach hashtable