UsefulTools.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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 |
function Set-TimeStampPrompt { <# .DESCRIPTION This function will add time stamp to current console prompt. .EXAMPLE DateEcho "This message need a timesamp" 26.01.2017-22:24:08> This message need a timesamp .EXAMPLE Set-TimeStampPrompt PS [08/31/2017 12:20:09] C:\Users\> .EXAMPLE Set-TimeStampPrompt -disable PS C:\Users\> #> param([switch]$disable=$false) if(-not $disable) { function global:Prompt { "PS "+ " [$(Get-Date)] " + $(get-location) +"> " } } else { function global:Prompt { "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "; # .Link # https://go.microsoft.com/fwlink/?LinkID=225750 # .ExternalHelp System.Management.Automation.dll-help.xml } } } function DateEcho($Var) { <# .DESCRIPTION This function will add an extra time stamp for all input. Pipeline enabled command. .EXAMPLE DateEcho "This message need a timesamp" 26.01.2017-22:24:08> This message need a timesamp .EXAMPLE ping 8.8.8.8 -t | DateEcho 26.01.2017-22:24:48> Reply from 8.8.8.8: bytes=32 time=10ms TTL=57 26.01.2017-22:24:49> Reply from 8.8.8.8: bytes=32 time=13ms TTL=57 26.01.2017-22:24:50> Reply from 8.8.8.8: bytes=32 time=12ms TTL=57 26.01.2017-22:24:51> Reply from 8.8.8.8: bytes=32 time=10ms TTL=57 26.01.2017-22:24:52> Reply from 8.8.8.8: bytes=32 time=10ms TTL=57 #> process { $TimeStamp=Get-Date -Format "dd.MM.yyyy-HH:mm:ss> " "$TimeStamp$Var$_" } } function Lock-WorkStation { <# .DESCRIPTION This function will lock the screen on workstation .EXAMPLE Lock-WorkStation #> rundll32.exe user32.dll, LockWorkStation } function Get-UpTimeStatistics { #System can start or stop #Start event can be InstanceID 1 or 2147489653 #Stop event can be InstanceID 41 or 2147489654 #need to find each start stop pair and caculat a difference and sum it. #Additional: Log the first start and last stop event and caculate as total #If system shutdown unexpected, two start log will follow each other #log the last proceed event log, if both was start event, #than check previous log for last online state and handle as a start stop pair <# .DESCRIPTION This function Will list all system up-time related events and calculate a usage statistics based on these event logs. .EXAMPLE Get-UpTimeStatistics ... Sytem Wake up at :07/09/2017 13:57:02 - Sleep at: 07/09/2017 16:59:43 | Total uptime: 10961(3:2:41) Sytem Wake up at :07/09/2017 18:57:33 - Sleep at: 07/09/2017 22:50:31 | Total uptime: 13978(3:52:58) Sytem Wake up at :07/09/2017 23:00:24 - Sleep at: 07/09/2017 23:21:41 | Total uptime: 1277(0:21:17) Sytem Wake up at :07/10/2017 07:53:26 - Sleep at: 07/10/2017 07:54:34 | Total uptime: 68(0:1:8) Sytem Wake up at :07/10/2017 07:54:50 - Sleep at: 07/10/2017 07:54:59 | Total uptime: 9(0:0:9) Sytem Wake up at :07/10/2017 09:05:35 - Sleep at: 07/10/2017 11:30:12 | Total uptime: 8677(2:24:37) Total Uptime: 815631(9 Day, 10:33:51) Total time: 2351273(27 Day, 5:7:53) Uptime Percent: 34.6889110707264 #> $var=Get-EventLog -LogName system -InstanceId 42 $var+=Get-EventLog -LogName system -InstanceId 1 -Source Microsoft-Windows-Power-Troubleshooter $var+=Get-EventLog -LogName system -Source EventLog | where Message -match ".*started|stopped.*" $var= $var | sort Index #clear-host $var "`n" $wakeUpTime=$null; $totalUpTime=0; $FirstWakUpTime=0 $LastSleepTime=0 $LastEventType="stopped" $LastEvent=$null foreach($next in $var) { #sleep or shutdown event if($next.InstanceID -eq 42 -or $next.InstanceId -eq 2147489654) { #check if there was any wakeuptime event already proceed. if($wakeUpTime -ne $null) { #calculate elapsed time between start and stop event $uptime=($next.TimeGenerated-$wakeUpTime).TotalSeconds $TimeSpan=New-TimeSpan -Seconds $uptime #Log information to display "Sytem Wake up at :" + $wakeUpTime + " - Sleep at: " + $next.TimeGenerated + " | Total uptime: " + $uptime+"("+$TimeSpan.Hours.ToString()+":"+$TimeSpan.Minutes.ToString()+":"+$TimeSpan.Seconds.ToString()+")" #Add currnet uptime to total $totalUpTime+=$uptime #save last sleep time for total time calculation $LastSleepTime=$next.TimeGenerated #save eventtype $LastEventType="stopped" } } #Wake Up event if($next.InstanceID -eq 1 -or $next.InstanceId -eq 2147489653)#wakupEvent { #This required to monitor previous monitored event was start or stopped type, #if previous was start than there was an unexpected shutdown, and need to check last recorded online state on EventLog source. if($LastEventType -eq "started" -and $lastEvent.InstanceID -eq 2147489653) { #filter eventlog event before $next event to determinate the last online state $var2=Get-EventLog -LogName system -Source EventLog | where index -lt $next.Index | select -First 10 #calculate elapsed time between start and stop event, #The shutdown time is the last recorded online time on EventLog source ( just before $next event) $uptime=($var2[3].TimeGenerated-$wakeUpTime).TotalSeconds $TimeSpan=New-TimeSpan -Seconds $uptime #Log information to display "Sytem Wake up at :" + $wakeUpTime + " - Sleep at: " + $var2[3].TimeGenerated + " | Total uptime: " + $uptime+"("+$TimeSpan.Hours.ToString()+":"+$TimeSpan.Minutes.ToString()+":"+$TimeSpan.Seconds.ToString()+")" #Add currnet uptime to total $totalUpTime+=$uptime #save last sleep time for total time calculation $LastSleepTime=$var2[3].TimeGenerated } #store the last wakuptime $wakeUpTime=$next.TimeGenerated #save the first Wake up time for total time estimation if($FirstWakUpTime -eq 0) { $FirstWakUpTime=$next.TimeGenerated } #save last event log and type $LastEventType="started" $LastEvent=$next } } $TimeSpan=New-TimeSpan -Seconds $totalUpTime "`nTotal Uptime: " + $totalUpTime+"("+$TimeSpan.Days.ToString()+" Day, "+$TimeSpan.Hours.ToString()+":"+$TimeSpan.Minutes.ToString()+":"+$TimeSpan.Seconds.ToString()+")" $TotalTime=$LastSleepTime-$FirstWakUpTime $TimeSpan=New-TimeSpan -Seconds $TotalTime.TotalSeconds "`nTotal time: " + $TotalTime.TotalSeconds+"("+$TimeSpan.Days.ToString()+" Day, "+$TimeSpan.Hours.ToString()+":"+$TimeSpan.Minutes.ToString()+":"+$TimeSpan.Seconds.ToString()+")" $UpTimePercent=$totalUpTime/$TotalTime.TotalSeconds*100 "`nUptime Percent: $UpTimePercent" } $signature = @" [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); public static IntPtr FindWindow(string windowName){ return FindWindow(null,windowName); } [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X,int Y, int cx, int cy, uint uFlags); [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); const UInt32 SWP_NOSIZE = 0x0001; const UInt32 SWP_NOMOVE = 0x0002; const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE; public static void MakeTopMost (IntPtr fHandle) { SetWindowPos(fHandle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS); } public static void MakeNormal (IntPtr fHandle) { SetWindowPos(fHandle, HWND_NOTOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS); } "@ $app = Add-Type -MemberDefinition $signature -Name Win32Window -Namespace ScriptFanatic.WinAPI -ReferencedAssemblies System.Windows.Forms -Using System.Windows.Forms -PassThru function Set-AlwaysOnTop { <# .DESCRIPTION This function will set or disable this console window to always on top. .PARAMETER Disable This option will disable always on top settings for current console windows. .EXAMPLE Set-AlwaysOnTop Set-AlwaysOnTop -Disable #> param( #[Parameter(Position=0,ValueFromPipelineByPropertyName=$true)][Alias('MainWindowHandle')]$hWnd=0, [Parameter()][switch]$Disable ) $hWnd=(Get-Process -Id $pid).MainWindowHandle if($hWnd -ne 0) { if($Disable) { Write-Verbose "Set process handle :$hWnd to NORMAL state" $null = $app::MakeNormal($hWnd) return } Write-Verbose "Set process handle :$hWnd to TOPMOST state" $null = $app::MakeTopMost($hWnd) } else { Write-Verbose "$hWnd is 0" } } $QuickEditCodeSnippet=@" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; public static class DisableConsoleQuickEdit { const uint ENABLE_QUICK_EDIT = 0x0040; // STD_INPUT_HANDLE (DWORD): -10 is the standard input device. const int STD_INPUT_HANDLE = -10; [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("kernel32.dll")] static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode); [DllImport("kernel32.dll")] static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode); public static bool SetQuickEdit(bool SetEnabled) { IntPtr consoleHandle = GetStdHandle(STD_INPUT_HANDLE); // get current console mode uint consoleMode; if (!GetConsoleMode(consoleHandle, out consoleMode)) { // ERROR: Unable to get console mode. return false; } // Clear the quick edit bit in the mode flags if (SetEnabled) { consoleMode &= ~ENABLE_QUICK_EDIT; } else { consoleMode |= ENABLE_QUICK_EDIT; } // set the new mode if (!SetConsoleMode(consoleHandle, consoleMode)) { // ERROR: Unable to set console mode return false; } return true; } } "@ $QuickEditMode=add-type -TypeDefinition $QuickEditCodeSnippet -Language CSharp function Set-QuickEdit() { <# .DESCRIPTION This function will set or disable the quick edit settings of this console window. Can be very useful to avoid accidently interrupt long running Powershell scripts by mouse clicking. .PARAMETER Disable This option will quick edit option on this console window. .EXAMPLE Set-AlwaysOnTop Set-AlwaysOnTop -DisableQuickEdit #> [CmdletBinding()] param( [Parameter(Mandatory=$false, HelpMessage="This switch will disable Console QuickEdit option")] [switch]$DisableQuickEdit=$false ) if([DisableConsoleQuickEdit]::SetQuickEdit($DisableQuickEdit)) { Write-Output "QuickEdit settings has been updated." } else { Write-Output "Something went wrong." } } Function Watch() { <# .DESCRIPTION This function a simplified clone of linux watch command. It will execute the given command periodicly .PARAMETER Delay You can specify the delay time between two command execution. .PARAMETER KeepLog This switch will keep the history of the continues command execution. .PARAMETER CommandString Specify the command that you want to monitor. If command contain space, use "" .EXAMPLE watch -Delay 1 -CommandString "Get-publicip" -KeepLog watch -CommandString "show-ipconfig 'Wifi Adapter'" #> [CmdletBinding()] param( [Parameter(Mandatory=$false, HelpMessage="Set sleep time for refresh")][int]$Delay=1, [Parameter(Mandatory=$false, HelpMessage="This switch will keep the console history")][switch]$KeepLog=$false, [Parameter(Mandatory=$true, HelpMessage="Define command to monitor")][string]$CommandString ) $cmd = [scriptblock]::Create($CommandString); while($true) { $time=get-date $time="$time | $CommandString `n----------------------------------------------------------------------------------`n`n" if(-not $KeepLog) { Clear-Host $time } $cmd.Invoke(); sleep $Delay } } |