Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch file for changes and run command with powershell

Is there any simple way(i.e., script) to watch file in Powershell and run commands if file changes. I have been googling but can't find simple solution. Basically I run script in Powershell and if file changes then Powershell run other commands.

EDIT

Ok I think I made a mistake. I don't need script, a need function that I can include in my $PROFILE.ps1 file. But still, I was trying hard and still I'm unable to write it, so I will give bounty. It have to look like this:

function watch($command, $file) {
  if($file #changed) {
    #run $command
  }
}

There is a NPM module that is doing what I want, watch , but it only watches for folders not files, and it's not Powershell xD.

like image 438
IGRACH Avatar asked Mar 15 '15 22:03

IGRACH


1 Answers

I will add another answer, because my previous one did miss the requirements.

Requirements

  • Write a function to WAIT for a change in a specific file
  • When a change is detected the function will execute a predefined command and return execution to the main script
  • File path and command are passed to the function as parameters

There is already an answer using file hashes. I want to follow my previous answer and show you how this can be accomplish using FileSystemWatcher.

$File = "C:\temp\log.txt"
$Action = 'Write-Output "The watched file was changed"'
$global:FileChanged = $false

function Wait-FileChange {
    param(
        [string]$File,
        [string]$Action
    )
    $FilePath = Split-Path $File -Parent
    $FileName = Split-Path $File -Leaf
    $ScriptBlock = [scriptblock]::Create($Action)

    $Watcher = New-Object IO.FileSystemWatcher $FilePath, $FileName -Property @{ 
        IncludeSubdirectories = $false
        EnableRaisingEvents = $true
    }
    $onChange = Register-ObjectEvent $Watcher Changed -Action {$global:FileChanged = $true}

    while ($global:FileChanged -eq $false){
        Start-Sleep -Milliseconds 100
    }

    & $ScriptBlock 
    Unregister-Event -SubscriptionId $onChange.Id
}

Wait-FileChange -File $File -Action $Action
like image 127
Jan Chrbolka Avatar answered Nov 03 '22 06:11

Jan Chrbolka