我想监控在文件夹中创建的新文件。 当发生这种情况时,我想启动批处理文件(在下面的示例中,我只是在日志文件中写一行)。 我不知道为什么这不起作用。
我的代码是:
$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}
答案 0 :(得分: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的文件,这意味着Apertura.txt无法使用,我建议使用类似Apertura的内容。*如果您不知道扩展名。
示例代码:
$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