Watch file for changes and run command with powershell

前端 未结 7 866
终归单人心
终归单人心 2020-11-28 07:01

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 scr

7条回答
  •  没有蜡笔的小新
    2020-11-28 07:42

    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
    

提交回复
热议问题