How To Watch in PowerShell

How To Watch in PowerShell

Every system administrator who runs a big system knows how to make long-running tasks less boring. Watching progress is one of those little fun things.

Sometimes, the count of the background processes or the size of the backup archive are the only signs that your system is alive and doing what's expected. Most modern Linux distros offer a watch utility to repeat the same command repeatedly. For example, the command below calculates the folder size every five seconds until you cancel it.

watch -n 5 "du -s /opt/backups"

Things change when you deal with the Windows system and miss the comfort of the good old terminal. Luckily, Windows PowerShell offers enough power to emulate the behavior and even create a makeshift utility that reproduces the original watch behavior.

param(
   $n=3 ,
   $cmd
)

while(1) { 
 "Every: $n sec  run: $cmd"
 "---------------------------------------------------------
 
 " 
 iex $cmd
 sleep $n;
 cls
}

The file watch.ps1

As simple as it is, PowerShell allows you to define parameters named or positional. It offers flow control and a mix of the standard DOS utilities with the Object-oriented native syntax. Here is a Windows counterpart to the Linux one above:

PS C:\> ./watch -n 5 -cmd "dir d:\backups" 

I'm ending my watch with a piece of advice: the script is in a location listed in the %PATH%, and it can run as any other PowerShell command.