PoshCode Logo PowerShell Code Repository

Start-Demo 3.3.1 by BSonPosh 9 years ago (modification of post by Joel Bennett view diff)
View followups from Joel Bennett | diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/302"></script>download | new post

This is an overhaul of Jeffrey Snover’s original Start-Demo script … I’ve switched it to use ReadKey, which saves you some typing and makes the whole thing seem more natural when you’re demoing, (at least to me). I’ve also added a bunch of command-line options and a couple of features in the process (see the Revision History in the script).

  1. ## Start-Demo.ps1
  2. ##################################################################################################
  3. ## This is an overhaul of Jeffrey Snover's original Start-Demo script by Joel "Jaykul" Bennett
  4. ##
  5. ## I've switched it to using ReadKey instead of ReadLine (you don't have to hit Enter each time)
  6. ## As a result, I've changed the names and keys for a lot of the operations, so that they make
  7. ## sense with only a single letter to tell them apart (sorry if you had them memorized).
  8. ##
  9. ## I've also been adding features as I come across needs for them, and you'll contribute your
  10. ## improvements back to the PowerShell Script repository as well.
  11. ##################################################################################################
  12. ## Revision History (version 3.3)
  13. ## 3.3.1 Added:    Fixed a bracket in the script
  14. ## 3.3 - Added:    Added a "Clear Screen" option
  15. ##     - Added:    Added a "Rewind" function (which I'm not using much)
  16. ## 3.2 - Fixed:    Put back the trap { continue; }
  17. ## 3.1 - Fixed:    No Output when invoking Get-Member (and other cmdlets like it???)
  18. ## 3.0 - Fixed:    Commands which set a variable, like: $files = ls
  19. ##     - Fixed:    Default action doesn't continue
  20. ##     - Changed:  Use ReadKey instead of ReadLine
  21. ##     - Changed:  Modified the option prompts (sorry if you had them memorized)
  22. ##     - Changed:  Various time and duration strings have better formatting
  23. ##     - Enhance:  Colors are settable: prompt, command, comment
  24. ##     - Added:    NoPauseAfterExecute switch removes the extra pause
  25. ##                 If you set this, the next command will be displayed immediately
  26. ##     - Added:    Auto Execute mode (FullAuto switch) runs the rest of the script
  27. ##                 at an automatic speed set by the AutoSpeed parameter (or manually)
  28. ##     - Added:    Automatically append an empty line to the end of the demo script
  29. ##                 so you have a chance to "go back" after the last line of you demo
  30. ##################################################################################################
  31. ##
  32. param(
  33.   $file=".\demo.txt",
  34.   [int]$command=0,
  35.   [System.ConsoleColor]$promptColor="Yellow",
  36.   [System.ConsoleColor]$commandColor="White",
  37.   [System.ConsoleColor]$commentColor="Green",
  38.   [switch]$FullAuto,
  39.   [int]$AutoSpeed = 3,
  40.   [switch]$NoPauseAfterExecute
  41. )
  42.  
  43. $RawUI = $Host.UI.RawUI
  44. $hostWidth = $RawUI.BufferSize.Width
  45.  
  46. # A function for reading in a character
  47. function Read-Char() {
  48.   $_OldColor = $RawUI.ForeGroundColor
  49.   $RawUI.ForeGroundColor = "Red"
  50.   $inChar=$RawUI.ReadKey("IncludeKeyUp")
  51.   # loop until they press a character, so Shift or Ctrl, etc don't terminate us
  52.   while($_input.Character -eq 0){
  53.     $inChar=$RawUI.ReadKey("IncludeKeyUp")
  54.   }
  55.   $RawUI.ForeGroundColor = $_OldColor
  56.   return $inChar.Character
  57. }
  58.  
  59. function Rewind($lines, $index, $steps = 1) {
  60.    $started = $index;
  61.    $index -= $steps;
  62.    while(($index -ge 0) -and ($lines[$index].Trim(" `t").StartsWith("#"))){
  63.       $index--
  64.    }
  65.    if( $index -lt 0 ) { $index = $started }
  66.    return $index
  67. }
  68.  
  69. $file = Resolve-Path $file
  70. while(-not(Test-Path $file)) {
  71.   $file = Read-Host "Please enter the path of your demo script (Crtl+C to cancel)"
  72.   $file = Resolve-Path $file
  73. }
  74.  
  75. Clear-Host
  76.  
  77. $_lines = Get-Content $file
  78. # Append an extra (do nothing) line on the end so we can still go back after the last line.
  79. $_lines += "Write-Host 'The End'"
  80. $_starttime = [DateTime]::now
  81. $FullAuto = $false
  82.  
  83. Write-Host -nonew -back black -fore $promptColor $(" " * $hostWidth)
  84. Write-Host -nonew -back black -fore $promptColor @"
  85. <Demo Started :: $(split-path $file -leaf)>$(' ' * ($hostWidth -(18 + $(split-path $file -leaf).Length)))
  86. "@
  87. Write-Host -nonew -back black -fore $promptColor "Press"
  88. Write-Host -nonew -back black -fore Red " ? "
  89. Write-Host -nonew -back black -fore $promptColor "for help.$(' ' * ($hostWidth -17))"
  90. Write-Host -nonew -back black -fore $promptColor $(" " * $hostWidth)
  91.  
  92. # We use a FOR and an INDEX ($_i) instead of a FOREACH because
  93. # it is possible to start at a different location and/or jump
  94. # around in the order.
  95. for ($_i = $Command; $_i -lt $_lines.count; $_i++)
  96. {  
  97.         # Put the current command in the Window Title along with the demo duration
  98.         $Dur = [DateTime]::Now - $_StartTime
  99.   $RawUI.WindowTitle = "$(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s   {3}" -f
  100.                         $dur.Hours, $dur.Minutes, $dur.Seconds, $($_Lines[$_i])
  101.  
  102.         # Echo out the commmand to the console with a prompt as though it were real
  103.         Write-Host -nonew -fore $promptColor "[$_i]PS> "
  104.         if ($_lines[$_i].Trim(" ").StartsWith("#")) {
  105.                 Write-Host -fore $commentColor "$($_Lines[$_i])  "
  106.                 continue
  107.         } else {
  108.                 Write-Host -nonew -fore $commandColor "$($_Lines[$_i])  "
  109.         }
  110.  
  111.         if( $FullAuto ) { Start-Sleep $autoSpeed; $ch = [char]13 } else { $ch = Read-Char }
  112.         switch($ch)
  113.         {
  114.                 "?" {
  115.                         Write-Host -Fore $promptColor @"
  116.  
  117. Running demo: $file
  118. (n) Next       (p) Previous
  119. (q) Quit       (s) Suspend
  120. (t) Timecheck  (v) View $(split-path $file -leaf)
  121. (g) Go to line by number
  122. (f) Find lines by string
  123. (a) Auto Execute mode
  124. (c) Clear Screen
  125. "@
  126.                         $_i-- # back a line, we're gonna step forward when we loop
  127.                 }
  128.                 "n" { # Next (do nothing)
  129.                         Write-Host -Fore $promptColor "<Skipping Line>"
  130.                 }
  131.                 "p" { # Previous
  132.                         Write-Host -Fore $promptColor "<Back one Line>"
  133.                         while ($_lines[--$_i].Trim(" ").StartsWith("#")){}
  134.                         $_i-- # back a line, we're gonna step forward when we loop
  135.                 }
  136.                 "x" { # EXECUTE (Go Faster)
  137.                         $AutoSpeed = [int](Read-Host "Pause (seconds)")
  138.                         $FullAuto = $true;
  139.                         Write-Host -Fore $promptColor "<eXecute Remaining Lines>"
  140.                         $_i-- # Repeat this line, and then just blow through the rest
  141.                 }
  142.                 "q" { # Quit
  143.                         Write-Host -Fore $promptColor "<Quiting demo>"
  144.                         $_i = $_lines.count;
  145.                         break;
  146.                 }
  147.                 "v" { # View Source
  148.                         $lines[0..($_i-1)] | Write-Host -Fore Yellow
  149.                         $lines[$_i]        | Write-Host -Fore Green
  150.                         $lines[($_i+1)..$lines.Count] | Write-Host -Fore Yellow
  151.                         $_i-- # back a line, we're gonna step forward when we loop
  152.                 }
  153.                 "t" { # Time Check
  154.                          $dur = [DateTime]::Now - $_StartTime
  155.        Write-Host -Fore $promptColor $(
  156.           "{3} -- $(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s" -f
  157.           $dur.Hours, $dur.Minutes, $dur.Seconds, ([DateTime]::Now.ToShortTimeString()))
  158.                          $_i-- # back a line, we're gonna step forward when we loop
  159.                 }
  160.                 "s" { # Suspend (Enter Nested Prompt)
  161.                         Write-Host -Fore $promptColor "<Suspending demo - type 'Exit' to resume>"
  162.                         $Host.EnterNestedPrompt()
  163.                         $_i-- # back a line, we're gonna step forward when we loop
  164.                 }
  165.                 "g" { # GoTo Line Number
  166.                         $i = [int](Read-Host "line number")
  167.                         if($i -le $_lines.Count) {
  168.                                 if($i -gt 0) {
  169.                # extra line back because we're gonna step forward when we loop
  170.                $_i = Rewind $_lines $_i (($_i-$i)+1)
  171.                                 } else {
  172.                                         $_i = -1 # Start negative, because we step forward when we loop
  173.                                 }
  174.                         }
  175.                 }
  176.                 "f" { # Find by pattern
  177.                         $match = $_lines | Select-String (Read-Host "search string")
  178.                         if($match -eq $null) {
  179.                                 Write-Host -Fore Red "Can't find a matching line"
  180.                         } else {
  181.                                 $match | % { Write-Host -Fore $promptColor $("[{0,2}] {1}" -f ($_.LineNumber - 1), $_.Line) }
  182.                                 if($match.Count -lt 1) {
  183.                                         $_i = $match.lineNumber - 2  # back a line, we're gonna step forward when we loop
  184.                                 } else {              
  185.                                         $_i-- # back a line, we're gonna step forward when we loop
  186.                                 }
  187.                         }
  188.                 }
  189.       "c" {
  190.          Clear-Host
  191.          $_i-- # back a line, we're gonna step forward when we loop
  192.       }
  193.                 "$([char]13)" { # on enter
  194.                         Write-Host
  195.                         trap [System.Exception] {Write-Error $_; continue;}
  196.                         Invoke-Expression ($_lines[$_i]) | out-default
  197.                         if(-not $NoPauseAfterExecute -and -not $FullAuto) {
  198.                                 $null = $RawUI.ReadKey("NoEcho,IncludeKeyUp")  # Pause after output for no apparent reason... ;)
  199.                         }
  200.                 }
  201.                 default
  202.                 {
  203.                         Write-Host -Fore Green "`nKey not recognized.  Press ? for help, or ENTER to execute the command."
  204.                         $_i-- # back a line, we're gonna step forward when we loop
  205.                 }
  206.         }
  207. }
  208. $dur = [DateTime]::Now - $_StartTime
  209. Write-Host -Fore $promptColor $(
  210.    "<Demo Complete -- $(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s>" -f
  211.    $dur.Hours, $dur.Minutes, $dur.Seconds, [DateTime]::Now.ToLongTimeString())
  212. Write-Host -Fore $promptColor $([DateTime]::now)
  213. Write-Host

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me