2014-05-20 53 views
1

这是一种检测文件夹中是否添加了文件的方法吗?包含子文件夹。如何检测文件夹中是否添加了文件?

例如,检查文件夹c:\data-files\或其子文件夹中是否添加了任何文本文件*.txt

该文件夹也可以是另一台机器的共享文件夹。

+1

http://gallery.technet.microsoft.com/scriptcenter/Powershell-FileSystemWatche-dfd7084b – Cole9350

+0

FileSystemWatcher对象似乎不具有共享文件夹的工作。 – ca9163d9

+0

那么它可能*看起来*不工作,但它绝对工作...你只需要知道实际路径 – Cole9350

回答

1

也许你是对被触发的事件类型的困惑: http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher_events(v=vs.110).aspx

这应该工作,从上面的链接采取和修改您的要求:

#By BigTeddy 05 September 2011 

#This script uses the .NET FileSystemWatcher class to monitor file events in folder(s). 
#The advantage of this method over using WMI eventing is that this can monitor sub-folders. 
#The -Action parameter can contain any valid Powershell commands. I have just included two for example. 
#The script can be set to a wildcard filter, and IncludeSubdirectories can be changed to $true. 
#You need not subscribe to all three types of event. All three are shown for example. 
# Version 1.1 

$folder = '\\remote\shared' # Enter the root path you want to monitor. 
$filter = '*.txt' # You can enter a wildcard filter here. 

# In the following line, you can change 'IncludeSubdirectories to $true if required.       
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 

# Here, all three events are registerd. You need only subscribe to events that you need: 

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { 
$name = $Event.SourceEventArgs.Name 
$changeType = $Event.SourceEventArgs.ChangeType 
$timeStamp = $Event.TimeGenerated 
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green 
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"} 

请注意,一旦你关闭powershell控制台fileSystemWatcher被扔掉,并不再监视文件夹。所以你必须确保PowerShell窗口保持打开状态。为了做到这一点,没有它在你的方式,我建议计划任务http://blogs.technet.com/b/heyscriptingguy/archive/2011/01/12/use-scheduled-tasks-to-run-powershell-commands-on-windows.aspx

相关问题