Watch file for changes and run command with powershell

前端 未结 7 868
终归单人心
终归单人心 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:38

    Here is another option.

    I just needed to write my own to watch and run tests within a Docker container. Jan's solution is much more elegant, but FileSystemWatcher is broken within Docker containers presently. My approach is similar to Vasili's, but much lazier, trusting the file system's write time.

    Here's the function I needed, which runs the command block each time the file changes.

    function watch($command, $file) {
        $this_time = (get-item $file).LastWriteTime
        $last_time = $this_time
        while($true) {
            if ($last_time -ne $this_time) {
                $last_time = $this_time
                invoke-command $command
            }
            sleep 1
            $this_time = (get-item $file).LastWriteTime
        }
    }
    

    Here is one that waits until the file changes, runs the block, then exits.

    function waitfor($command, $file) {
        $this_time = (get-item $file).LastWriteTime
        $last_time = $this_time
        while($last_time -eq $this_time) {
            sleep 1
            $this_time = (get-item $file).LastWriteTime
        }
        invoke-command $command
    }
    

提交回复
热议问题