Skip to content

Instantly share code, notes, and snippets.

@johannesprinz
Last active December 3, 2017 23:13
Show Gist options
  • Save johannesprinz/7e04f50a1143d6a795f8893eae6d61dc to your computer and use it in GitHub Desktop.
Save johannesprinz/7e04f50a1143d6a795f8893eae6d61dc to your computer and use it in GitHub Desktop.
Testing PowerShell function with timer and writing progress and also seeing the interesting pipeline management in action
function Test-TimedProcessFunction {
[OutputType([String])]
[CmdletBinding(
SupportsShouldProcess=$true,
ConfirmImpact="None"
)]
param (
[Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[string]$Name,
[Parameter(Position=2, ValueFromPipeline=$true)]
[ValidateRange(1,10)]
[int]$Iteration = 1
)
Begin{
$formats = @{
"Begin" = "Begin {0}...";
"Process" = "...processing {0}...";
"End" = "...ending {0}";
};
Write-Verbose -Message ($formats.Begin -f "$($MyInvocation.MyCommand) $(Get-Date -Format o)");
$timer = [System.Diagnostics.Stopwatch]::StartNew();
$totalTime = $timer.Elapsed;
} Process {
if ($pscmdlet.ShouldProcess($Name)) {
for($i = 0; $i -lt $Iteration; $i++ ){
Write-Progress -Id $MyInvocation.PipelinePosition -Activity $MyInvocation.MyCommand -Status "Total time:$($totalTime.ToString())" -PercentComplete $($i/$Iteration*100) -CurrentOperation $($timer.Elapsed.ToString()+" $Name");
Write-Verbose -Message ($formats.Process -f $MyInvocation.MyCommand);
"$Name$i";
}
}
$totalTime += $timer.Elapsed;
$timer.Restart();
} End {
Write-Progress -Id $MyInvocation.PipelinePosition -Activity $MyInvocation.MyCommand -Completed;
$timer.Stop();
Write-Verbose -Message ($formats.End -f "$($MyInvocation.MyCommand) $($timer.Elapsed.ToString())");
}
}
"Bob","Charlie","Marry","1","2","3","4","5" | Test-TimedProcessFunction -Iteration 5 | Test-TimedProcessFunction -Iteration 2 | Test-TimedProcessFunction -Iteration 10 | Out-Null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment