코드가 오류없이 실행되지만 파일 시스템에서 파일을 추가/삭제할 때 코드가 수행 할 작업은 Register-ObjectEvent $watcher "watchType" -Action $action
입니다. 과거에는 파일이 삭제되었거나 추가 된 날짜와 날짜를 log.txt
에 작성/추가했기 때문에이 사실을 알고 있습니다. 이제 아무 일도 일어나지 않습니다. 무슨 일 이니?PowerShell : FileSystemWatcher가 작동하지 않습니다.
코드 :
#local path of the folder you want to sync. By default sets to current directory
$localPath = get-location
#filter specific files by name/type
$filter = "*.*"
#include subdirectories
$inclSubDirectories = $true
#end of user defined variables
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $localPath
$watcher.Filter = $filter
$watcher.IncludeSubdirectories = $inclSubDirectories
$watcher.EnableRaisingEvents = $true
$oldContent = ""
$action = {
$path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
Add-content "'$localPath'\log.txt" -value $logline
}
$created = Register-ObjectEvent $watcher "Created" -Action $action
$action1 = {
$path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
Add-content "'$localPath'\log.txt" -value $logline
}
$deleted = Register-ObjectEvent $watcher "Deleted" -Action $action1
$exitAction = {
"File wathcer unregistered!"
Unregister-Event $created
Unregister-Event $deleted
}
$exit = Register-EngineEvent PowerShell.Exiting -action $exitAction
while ($true) {
if($oldContent -eq $logline){}
else{
$logline
$oldContent = $logline
}
Start-Sleep -m 1000
}
내가 복사 PowerShell을 직접 코드를 붙여 넣으려고하기로 결정
편집, 그리고 그것을가 예상대로 작동 ... 없음 완전히, 그것은 아무튼 출력은되지만 log.txt는 어떻게 업데이트해야합니까? 실제로는 한 번만 작동했습니다. 이제는 이전과 같은 모습으로 돌아 왔습니다.
편집 v2를
이벤트 (다음 생성, 삭제) 나는 경우 예를 들어, 그 다음은 것, 로그에 삭제 한 파일을 등록 할 (PowerShell을에 복사 - 붙여 넣기 한 번만 작동하는 것 같다생성 된 파일을 등록하되 다른 일은하지 않을 것입니다.) 여전히 출력해야하는 것처럼 출력되지 않습니다.
나는'동안 ($ true)가'루프가 완전히 블록이 이벤트 콜백이 예상되는 메인 스레드를 실행할 생각합니다. 왜 그것을 필요로합니까? – wOxxOm
@wOxxOm 루프 섹션을 주석 처리했으며 스크립트가 스크립트의 끝에 도달했기 때문에 스크립트가 닫힙니다. 또한 작동하기 전에 루프가 있었기 때문에 문제가 있다고 생각하지 않습니다. –
루프 내부에 적어도 Start-Sleep -Milliseconds 100이 없으면 여전히 잘못되었다고 생각합니다. – wOxxOm