2017-07-24 84 views
1

我想監視在文件夾中創建的新文件。 當發生這種情況時,我想啓動一個批處理文件(在下面的示例中,我只是在日誌文件中寫入一行)。 我不知道爲什麼這不起作用。不同文件的差異操作

我的代碼是:

$watcher = New-Object System.IO.FileSystemWatcher 
$watcher.Path = "D:\" 
$watcher.Filter = "*.*" 
$watcher.IncludeSubdirectories = $true 
$watcher.EnableRaisingEvents = $true 

$action = { 
    $path = $Event.SourceEventArgs.FullPath 
    $changeType = $Event.SourceEventArgs.ChangeType 
    $logline = "$(Get-Date), $changeType, $path" 

    if ($file.Name -like "Apertura") { 
     Add-Content "C:\Users\F701845\Desktop\Apertura.txt" -Value $logline 
    } else { 
     Add-Content "C:\Users\F701845\Desktop\TestNO.txt" -Value $logline 
    } 
} 

Register-ObjectEvent $watcher "Created" -Action $action 
while ($true) {sleep 5} 
+4

請說明它是如何失敗的 - 有一個在失敗的代碼沒有明顯的理由,因此任何相關的錯誤信息將是有益的。 –

+1

我的猜測是,'$ file.Name-like「Apertura」'應該是'$ file.Name -like「* Apertura *」'''''''''不帶'*'作爲通配符與'-eq ' – BenH

回答

1

嗯,這一個,你使用的變量,在你的if/else空很容易。 $ path和$ changeType是從$ Event派生的,但$ file根本不存在。

首先看看你有什麼,你會發現你可能會在這種情況下使用:$ Event.SourceEventArgs.Name。

$Event.SourceEventArgs | Get-Member 

bool Equals(System.Object obj) 
int GetHashCode() 
type GetType() 
string ToString() 
System.IO.WatcherChangeTypes ChangeType {get;} 
string FullPath {get;} 
string Name {get;} 

雖然它的工作,但它仍然會查找名爲正是春季文件意味着Apertura.txt不會工作,我會建議使用像春季。*如果你不知道分機。

示例代碼:

$watcher = New-Object System.IO.FileSystemWatcher 
$watcher.Path = "C:\test\" 
$watcher.Filter = "*.*" 
$watcher.IncludeSubdirectories = $true 
$watcher.EnableRaisingEvents = $true 

$action = { 

    $path = $Event.SourceEventArgs.FullPath 
    $changeType = $Event.SourceEventArgs.ChangeType 
    $file = $Event.SourceEventArgs.Name #get filename from Event data 
    $logline = "$(Get-Date), $changeType, $path" 

    if ($file -like "Apertura.*") { #removed the .Name and added .* 
     Add-Content "C:\Users\username\Desktop\Apertura.txt" -Value $logline 
    } else { 
     Add-Content "C:\Users\username\Desktop\TestNO.txt" -Value $logline 
    } 
} 

Register-ObjectEvent $watcher "Created" -Action $action 
while ($true) {sleep 5} 

$watcher.Dispose() #can be used to dispose the System.IO.FileSystemWatcher