我正在尝试在Powershell中使用$ FileSystemWatcher,它在由程序生成时似乎会丢失某些更改。
机器的一个应用程序会生成一个xml文件,该文件包含用于生成零件的参数。通过机器附带的软件进行修改时,我看到上次修改的日期已更改。但是,我没有注册任何活动。
如果我获取xml文件,请将其打开,修改并关闭,然后将事件注册。
下面是我使用的代码。
关于原因和解决方案的任何想法吗?
$PathToMonitor = "C:\Test"
$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path = $PathToMonitor
$FileSystemWatcher.Filter= "product.xml"
$FileSystemWatcher.IncludeSubdirectories = $true
$FileSystemWatcher.EnableRaisingEvents = $true
$previoustimestamp = $null
$previousfullpath = $null
# define the code that should execute when a file change is detected
$Action = {
$Timestamp = $event.TimeGenerated
$details = $event.SourceEventArgs
$FullPath = $details.FullPath
if (($previoustimestamp -ne $Timestamp) -and ($previousfullpath -ne $FullPath)){
$previoustimestamp= $Timestamp
$previousfullpath = $FullPath
$Name = $details.Name
$FullPath = $details.FullPath
$OldFullPath = $details.OldFullPath
$OldName = $details.OldName
$ChangeType = $details.ChangeType
# you can also execute code based on change type here
switch ($ChangeType)
{
'Changed' { "CHANGED"
$OriginalPath=$FullPath.split("\")
$OriginalPath=$OriginalPath[0]+"\"+$OriginalPath[1]+"\"+$OriginalPath[2]+"\"+$OriginalPath[3]+"\"+ $OriginalPath[4]+"\"
$RecipeFolder=$OriginalPath.split("\")
$RecipeFolder=$RecipeFolder[4]
Write-Host $RecipeFolder[4]
$OriginalRecipeFolder=$RecipeFolder
$RecipeFolder+="_"+$timeStamp
$NewRecipeFolder=$RecipeFolder.Replace("/","_").Replace(" ","_").Replace(":","_")
$BackupPath=$OriginalPath.Replace("Products","Backup").Replace($OriginalRecipeFolder,$NewRecipeFolder)
Copy-Item -Path $OriginalPath -Destination $BackupPath -Recurse
Write-Host "Backup done of recipe $OriginalRecipeFolder from $OriginalPath to $BackupPath at $timeStamp because $changetype" -ForegroundColor Yellow
Start-Sleep -Seconds 5
}
}
}
}
# add event handlers
$handlers = . {
Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Changed -Action $Action -SourceIdentifier FsChange
#FSCreate FSDelete FSRename
}
Write-Host "Watching for changes to $PathToMonitor"
try
{
do
enter code here
{
Wait-Event -Timeout 1
Write-Host "." -NoNewline
} while ($true)
}
finally
{
# this gets executed when user presses CTRL+C
# remove the event handlers
Unregister-Event -SourceIdentifier FSChange
# remove background jobs
$handlers | Remove-Job
# remove filesystemwatcher
$FileSystemWatcher.EnableRaisingEvents = $false
$FileSystemWatcher.Dispose()
"Event Handler disabled."
}