Watch a File for Change

How to watch a file, whenever it changes, take the new additional line and perform some actions on it with powershell

What you are doing is only allowed to show a file in real-time on the screen. You cannot mess with the output doing that.

The command you are using is not for interactive use cases.

You can monitor for file updates without doing what you are doing, by using a SystemFileWatcher, which allows for monitor for file actions, that you can then take action on.



'PowerShell filesystemwatcher monitor file'

https://duckduckgo.com/?q=%27PowerShell+filesystemwatcher+monitor+file%27&t=h_&ia=web


For example from one of the hits from the above link.

https://powershell.one/tricks/filesystem/filesystemwatcher

Monitoring Folders for File Changes

With a FileSystemWatcher, you can monitor folders for file changes and
respond immediately when changes are detected. This way, you can
create “drop” folders and respond to log file changes.

Specifically, as per your use case:

Advanced Mode (asynchonous)

If you expect changes to happen in rapid succession or even
simultaneously, you can use the FileSystemWatcher in asynchronous
mode: the FileSystemWatcher now works in the background and no longer
blocks PowerShell. Instead, whenever a change occurs, an event is
raised. So with this approach, you get a queue and won’t miss any
change.

On the back side, this approach has two challenges:

  • Handling Events: since PowerShell is single-threaded by nature, it is
    not trivial to respond to events, and even more cumbersome to debug
    event handler code.

    Keeping PowerShell running: ironically, because the FileSystemWatcher
    now no longer blocks PowerShell, this leads to another problem. You
    need to keep PowerShell waiting for events but you cannot use
    Start-Sleep or and endless loop because as long as PowerShell is busy

    • and it is considered busy even if it sleeps - no events can be handled.

Implementation

The script below does the exact same thing as the synchronous version
from above, only it is event-based and won’t miss any events anymore:

# find the path to the desktop folder:
$desktop = [Environment]::GetFolderPath('Desktop')

# specify the path to the folder you want to monitor:
$Path = $desktop

# specify which files you want to monitor
$FileFilter = '*'

# specify whether you want to monitor subfolders as well:
$IncludeSubfolders = $true

# specify the file or folder properties you want to monitor:
$AttributeFilter = [IO.NotifyFilters]::FileName, [IO.NotifyFilters]::LastWrite

try
{
$watcher = New-Object -TypeName System.IO.FileSystemWatcher -Property @{
Path = $Path
Filter = $FileFilter
IncludeSubdirectories = $IncludeSubfolders
NotifyFilter = $AttributeFilter
}

# define the code that should execute when a change occurs:
$action = {
# the code is receiving this to work with:

# change type information:
$details = $event.SourceEventArgs
$Name = $details.Name
$FullPath = $details.FullPath
$OldFullPath = $details.OldFullPath
$OldName = $details.OldName

# type of change:
$ChangeType = $details.ChangeType

# when the change occured:
$Timestamp = $event.TimeGenerated

# save information to a global variable for testing purposes
# so you can examine it later
# MAKE SURE YOU REMOVE THIS IN PRODUCTION!
$global:all = $details

# now you can define some action to take based on the
# details about the change event:

# let's compose a message:
$text = "{0} was {1} at {2}" -f $FullPath, $ChangeType, $Timestamp
Write-Host ""
Write-Host $text -ForegroundColor DarkYellow

# you can also execute code based on change type here:
switch ($ChangeType)
{
'Changed' { "CHANGE" }
'Created' { "CREATED"}
'Deleted' { "DELETED"
# to illustrate that ALL changes are picked up even if
# handling an event takes a lot of time, we artifically
# extend the time the handler needs whenever a file is deleted
Write-Host "Deletion Handler Start" -ForegroundColor Gray
Start-Sleep -Seconds 4
Write-Host "Deletion Handler End" -ForegroundColor Gray
}
'Renamed' {
# this executes only when a file was renamed
$text = "File {0} was renamed to {1}" -f $OldName, $Name
Write-Host $text -ForegroundColor Yellow
}

# any unhandled change types surface here:
default { Write-Host $_ -ForegroundColor Red -BackgroundColor White }
}
}

# subscribe your event handler to all event types that are
# important to you. Do this as a scriptblock so all returned
# event handlers can be easily stored in $handlers:
$handlers = . {
Register-ObjectEvent -InputObject $watcher -EventName Changed -Action $action
Register-ObjectEvent -InputObject $watcher -EventName Created -Action $action
Register-ObjectEvent -InputObject $watcher -EventName Deleted -Action $action
Register-ObjectEvent -InputObject $watcher -EventName Renamed -Action $action
}

# monitoring starts now:
$watcher.EnableRaisingEvents = $true

Write-Host "Watching for changes to $Path"

# since the FileSystemWatcher is no longer blocking PowerShell
# we need a way to pause PowerShell while being responsive to
# incoming events. Use an endless loop to keep PowerShell busy:
do
{
# Wait-Event waits for a second and stays responsive to events
# Start-Sleep in contrast would NOT work and ignore incoming events
Wait-Event -Timeout 1

# write a dot to indicate we are still monitoring:
Write-Host "." -NoNewline

} while ($true)
}
finally
{
# this gets executed when user presses CTRL+C:

# stop monitoring
$watcher.EnableRaisingEvents = $false

# remove the event handlers
$handlers | ForEach-Object {
Unregister-Event -SourceIdentifier $_.Name
}

# event handlers are technically implemented as a special kind
# of background job, so remove the jobs now:
$handlers | Remove-Job

# properly dispose the FileSystemWatcher:
$watcher.Dispose()

Write-Warning "Event Handler disabled, monitoring ends."
}

So, with the above, you tweak it to look for updates/modifications, then use

$CaptureLine = Get-Content -Path 'UNCToTheLogFile' | Select-Object -Last 1

Or

$CaptureLine = Get-Content -Path  'D:\temp\book1.csv' -Tail 1

And do what you want from that.

Can I watch for single file change with WatchService (not the whole directory)?

Just filter the events for the file you want in the directory:

final Path path = FileSystems.getDefault().getPath(System.getProperty("user.home"), "Desktop");
System.out.println(path);
try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
final WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
final WatchKey wk = watchService.take();
for (WatchEvent<?> event : wk.pollEvents()) {
//we only register "ENTRY_MODIFY" so the context is always a Path.
final Path changed = (Path) event.context();
System.out.println(changed);
if (changed.endsWith("myFile.txt")) {
System.out.println("My file has changed");
}
}
// reset the key
boolean valid = wk.reset();
if (!valid) {
System.out.println("Key has been unregisterede");
}
}
}

Here we check whether the changed file is "myFile.txt", if it is then do whatever.

Vue-cli-service: watch for file changes/recompile when edit

Ok, I found something.

This is an issue with WSL2 not being able to trigger file change notifications: https://github.com/microsoft/WSL/issues/4739 .

I tried using Vite and with adding:

server: {
watch: {
usePolling: true
}
}

To the vite.config.js, it does work properly with WSL2 as explained here.

Watch for file changes in Dart

You want to take a look at FileSystemEntity.watch() method. However due to platform differences some platforms provide better support than others. In particular, on Windows you can only watch a Directory, and not just an individual file. On Linux you can watch Files or Directories but not recursively watch Directories. And MacOS supports all of the above.

There is also a watcher package on Pub. This supports polling (periodically check if the file has changed) if the file system does not allow watching.

Is there a way to watch file changes in main js file runned in nodejs?

You can use nodemon. It will detect any changes to your directory and rerun the app.

npm install --save-dev nodemon
nodemon --inspect-brk index.js

forever node.js - watch directory for file changes

seems like u need nodemon

npm install -g nodemon

however in my windows server i used https://github.com/tjanczuk/iisnode good for scalability on multi core servers

How do I make Vite build my files every time a change is made?

If you want Vite to do a rebuild on file changes, you can use the --watch flag:

vite build --watch

In your case, with a custom config file:

vite build --watch --config vite.config.development.js

With the --watch flag enabled, changes to the config file, as well as any files to be bundled, will trigger a rebuild and will update the files in dist.



Related Topics



Leave a reply



Submit