Sometimes it suits me…
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 |
param ( [Parameter(Mandatory=$true)][string]$target, [Parameter(Mandatory=$false)][int]$waitUntilNextCycle=1, [Parameter(Mandatory=$false)][bool]$displayOkStatus=$true ) $ping = New-Object System.Net.NetworkInformation.Ping function Get-Timestamp { return [System.DateTime]::Now.ToString('HH:mm:ss') } if (!$displayOkStatus) { Write-Warning "Only connection errors will be displayed!" } while ($true) { try { $res = $ping.send($target) $status = $res.Status if ($status -ilike "Success") { if ($displayOkStatus) { Write-Host "[Ok $(Get-Timestamp)]" -NoNewline -BackgroundColor DarkGreen -ForegroundColor White } } else { Write-Host "[$status $(Get-Timestamp)]" -NoNewline -BackgroundColor DarkRed -ForegroundColor White } Start-Sleep -Seconds $waitUntilNextCycle } catch { Write-Host "[DNS or network connection error $(Get-Timestamp)]" -NoNewline -BackgroundColor Black -ForegroundColor White } } |
Most useful function
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function timestamp { case "$1" in 1) timestamp=`/bin/date '+%Y.%m.%d %k:%M:%S:%N'`;; 2) timestamp=`/bin/date '+%Y-%m-%d'`;; 3) timestamp=`/bin/date '+%Y-%m-%d'`;; 4) timestamp=`/bin/date '+%Y'`;; 5) timestamp=`/bin/date '+%k:%M'`;; *) timestamp=`/bin/date '+%Y.%m.%d %k:%M:%S'`;; esac echo $timestamp } echo "now is `timestamp 5`" |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function Get-Timestamp() { param ( [Parameter(Mandatory=$false)][string]$type="1" ) $Now = [System.DateTime]::Now switch($type) { 1 {[string]$ret = $Now.ToString("yyyy.MM.dd HH:mm:ss")} 2 {[string]$ret = $Now.ToString("yyyy.MM.dd")} 3 {[string]$ret = $Now.ToString("yyyy-MM-dd__HH-mm")} 4 {[string]$ret = $Now.ToString("yyyy-MM-dd")} 5 {[string]$ret = $Now.ToString("dddd")} 6 {[string]$ret = $Now.ToString("yyyyMMddHHmmss")} 7 {[string]$ret = $Now.ToString("yyyy.MM.dd HH:mm:ss.ff")} 8 {[string]$ret = $Now.ToString("yyyyMMddHHmmssff")} } return $ret } Write-Host "today is $(Get-Timestamp -type 5)" |
The script executes a commands stored in a variable (array). The output is conveniently collected and stored in a log file.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
[string]$log = "c:\temp\log.txt" [array]$commands = @( 'if (!([System.Environment]::OSVersion.Version).Major -ge 6) {"win xp"} else {"win 7 or higher"}'; 'gps | select id,@{Name="WorkingSet(MB)";Expression={"{0:N1} M" -f($_.WorkingSet/1mb)}},name,company | sort name | ft'; 'netstat -noa -p TCP | findstr /i close' ) foreach ($command in $commands) { $command = [scriptblock]::Create($command) [array]$output = & $command $output | fl | Out-File -FilePath $log -Encoding UTF8 -Append } |