Start-Watch.ps1

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<#
.SYNOPSIS
Watch a process in a loop for updated output.
 
.DESCRIPTION
Watch a process in a loop for updated output. This is an equivalent
of the linux watch command.
 
.NOTES
Author: John Rizzo @johnrizzo1
Modified by: Jason Wasser @wasserja
Created: 6/12/2014
Modified: 5/19/2017 10:40:18 AM
 
.EXAMPLE
Start-Watch -Interval 5 -Command 'netstat -an | Select-String :123'
 
Every 2s: netstat -an | Select-String :123 Friday, May 19, 2017 10:27:01 AM
 
UDP 0.0.0.0:123 *:*
UDP [::]:123 *:*
 
Watch netstat for port 123 access
 
.EXAMPLE
Start-Watch -Interval 5 -Command 'netstat -an | Select-String SYN'
 
Every 5s: netstat -an | Select-String SYN Friday, May 19, 2017 10:41:45 AM
 
TCP 10.111.161.155:59105 172.17.55.13:3333 SYN_SENT
.EXAMPLE
Start-Watch -Interval 10 -Command 'Get-ChildItem -Path C:\Logs'
 
Watch a directory for new files.
 
.PARAMETER Interval
Interval in seconds that the command should be repeated.
 
.PARAMETER Command
The command that you want to repeat every $Interval seconds.
The command MUST be wrapped in single or double quotes.
 
.LINK
http://johnrizzo.net/powershell-watch-script-command/
 
.LINK
http://mrautomaton.com
#>

function Start-Watch {
    [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')]
    [Alias('watch')]
    param (
        [Parameter(Mandatory = $False,
            ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True)]
        [alias('n')]
        [int]$Interval = 10,

        [Parameter(Mandatory = $True,
            ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True)]
        [string]$Command
    )
    process {
        $cmd = [scriptblock]::Create($command)
        While ($True) {
            Clear-Host
            Write-Host "Every $Interval`s: $Command `t$(Get-Date -Format F) `n" -ForegroundColor Green
            $cmd.Invoke()
            Start-Sleep -Seconds $Interval
        }
    }
}