2014-05-20 60 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

相關問題