PowerShell One-Liners: Watching output

Up, enter. Up, enter. Up, enter. Up, enter.

Those two keys are probably being mashed right now somewhere in the world as an engineer waits for a system to do something. Back in my *Nix days, I would have just thrown ‘watch’ in front of whichever command I wanted to keep an eye on and let the shell take care of things for me, but there isn’t quite an analogue in the Windows world.

We can do the same sort of thing, however, by issuing a one line command which repeats until you issue a control-C. For example:

while ($true) {clear;date;netstat -an | findstr LISTENING; sleep 5}

I was using this command today when working with a third party SIP server to make sure the service started listening on the right IP address, and kept refreshing every 5 seconds so I didn’t have to keep tabbing back to a powershell/cmd window to reissue a command.

The basic anatomy of this little script is this:

while ($true)                          # true is always true, so the loop always executes
{                                      # start of the loop
clear;                                 # clear the screen
date;                                  # print the date and time
netstat -an |findstr LISTENING;        # the command you wish to repeat
sleep 5                                # wait for X seconds. in this case 5.
}                                      # end of the loop

The clear and date at the start makes me feel like I’m using the Linux watch command, I guess. Old habits die hard. Note that this is still the same script as the first one, but I’ve just broken it out to separate lines and added comments (the stuff behind the hashes).

Other examples:

# Which services are running?
while ($true) {clear;date;Get-CsWindowsService;sleep 5}
# How are my routing groups looking after I rebooted one of my frontends?
while ($true) {clear;date;Get-CsPoolFabricState -PoolFqdn YourPool.domain.local;sleep 5}
# How many users are logged in before I start patching?
while ($true) {clear;date;(Get-CsUser -OnLyncServer).Count
# How many PSTN calls are active before I take down my mediation server?
while ($true) {clear;date;Get-CsWindowsService -Name RTCMEDSRV | select activitylevel;sleep 5}

We can even take that a step further, by setting a run limit. Let’s say that I wanted to run a command 10 times only. All I need to do is initialize a counter, set the script to only run if the counter is less than or equal to 10, and then get the loop to increment the counter by one each time.

$counter = 1
while ($counter -le 10) {clear;date;$counter;Get-CsWindowsService;sleep 5;$counter = $counter + 1}