Setup `watch` Alias in PowerShell
Setup `watch` Alias in PowerShell
The watch command is very helpful for monitoring commands in Linux. Unfortunately, Windows doesn’t have this command. This guide creates a custom watch function in PowerShell.
Create the Custom Function
Edit your $PROFILE:
1
notepad $PROFILE
Add the following function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function watch {
param (
[int]$interval = 5,
[Parameter(ValueFromRemainingArguments = $true)]
[string[]]$command
)
if (-not $command -or $command.Count -eq 0) {
Write-Host "❌ You must specify a command to watch. Example: watch 5 kubectl get pods"
return
}
$prevLineCount = 0
while ($true) {
[Console]::SetCursorPosition(0, 0)
try {
$output = Invoke-Expression ($command -join " ") | Out-String
$lines = $output -split "`r?`n"
foreach ($line in $lines) {
Write-Host $line
}
# Clear leftover lines from previous run
if ($lines.Count -lt $prevLineCount) {
for ($i = 0; $i -lt ($prevLineCount - $lines.Count); $i++) {
Write-Host (" " * [Console]::WindowWidth)
}
}
$prevLineCount = $lines.Count
} catch {
Write-Host "`n❌ Error: $_"
}
Start-Sleep -Seconds $interval
}
}
Reload the profile:
1
. $PROFILE
Usage
1
watch 5 kubectl get pods
This runs kubectl get pods every 5 seconds.
This post is licensed under CC BY 4.0 by the author.