Created
April 7, 2023 15:11
-
-
Save bixb0012/52b178550417cc4972a87d172a4be1bc to your computer and use it in GitHub Desktop.
PowerShell: Console-related
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Requires -Version 5.1 | |
# Reference: 1) https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.runspaces.runspace?view=powershellsdk-1.1.0 | |
# Reference: 2) https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.powershell?view=powershellsdk-1.1.0 | |
# Reference: 3) https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-progress?view=powershell-5.1 | |
# Reference: 4) https://learn.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=netframework-4.8.1 | |
# Example 1: Continuously watch Windows diagnostic counters in console progress bar | |
$Counters = @( # Windows diagnostic counter(s) | |
"\Processor(_total)\% Processor Time" | |
"\Memory\% Committed Bytes In Use" | |
) | |
$Interval = 3 # Interval for refreshing counter(s) | |
$RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, [Environment]::ProcessorCount/2) | |
$RunspacePool.Open() | |
try { | |
$Jobs = [Collections.ArrayList]@() | |
for ($i=0; $i -lt $Counters.Length; $i++) { | |
$ScriptBlock = [ScriptBlock]::Create("Get-Counter -Counter '$($Counters[$i])'") | |
$PowerShell = [PowerShell]::Create() | |
[void]$PowerShell.AddScript($ScriptBlock) | |
[void]$Jobs.Add([PSCustomObject]@{ | |
"AsyncResult" = $PowerShell.BeginInvoke() | |
"PowerShell" = $PowerShell | |
}) | |
} | |
while ($true) { | |
while ($Jobs.AsyncResult.IsCompleted -contains $false) { | |
Start-Sleep -Milliseconds 100 | |
} | |
for ($i=0; $i -lt $Counters.Length; $i++) { | |
$Counter = $Jobs[$i].PowerShell.EndInvoke($Jobs[$i].AsyncResult) | |
$ProgressArgs = @{ | |
"Activity" = $Counter.CounterSamples.Path | |
"Status" = "$($Counter.TimeStamp) : $($Counter.CounterSamples.CookedValue)" | |
"Id" = $i + 1 | |
"CurrentOperation" = " " | |
"ParentId" = 0 | |
} | |
Write-Progress @ProgressArgs | |
} | |
Start-Sleep -Milliseconds ($Interval * 1000 - 500) | |
for ($i=0; $i -lt $Counters.Length; $i++) { | |
$Jobs[$i].AsyncResult = $Jobs[$i].PowerShell.BeginInvoke() | |
} | |
} | |
} finally { | |
$Jobs | ForEach-Object { $_.PowerShell.Dispose() } | |
$RunspacePool.Dispose() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment