Advertisement
FatalBulletHit

SimpleUI

Oct 23rd, 2019 (edited)
635
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Param (
  2.  
  3.     [Parameter(Mandatory=$false,
  4.     Position=0)]
  5.     [switch] $DisableUpdateCheck,
  6.    
  7.     [Parameter(Mandatory=$false,
  8.     Position=1)]
  9.     [switch] $DontForce
  10.  
  11. )
  12.  
  13. <# https://pastebin.com/9RSusrvC
  14.  
  15. NOTE: Save this with UTF-8-BOM encoding!
  16.  
  17. The SimpleUI module improves user friendliness and readability of the PowerShell console and comes with a few gimmicks which contribute to an overall better console experience.
  18. Amongst other things it features a stable buffer width, correct word splitting, leading spaces, a simple three dot animation and a neat looking user prompt with some additional features.
  19.  
  20. For a preview paste the following lines into...
  21.  
  22. ... PowerShell:
  23.  
  24. # This will download the SimpleUI module as well as a preview script and then start the latter (make sure script execution is allowed)
  25. Set-Location $HOME\Downloads
  26. (Invoke-WebRequest -UseBasicParsing -Uri 'https://pastebin.com/raw/9RSusrvC').Content | Add-Content -Path .\SimpleUI.psm1 -Encoding UTF8
  27. (Invoke-WebRequest -UseBasicParsing -Uri 'https://pastebin.com/raw/e0n3mWy0').Content | Add-Content -Path .\SimpleUIPreview.ps1 -Encoding UTF8
  28. & .\SimpleUIPreview.ps1
  29.  
  30. ... cmd:
  31.  
  32. :: This will download the SimpleUI module as well as a preview script and then start the latter
  33. PowerShell -ExecutionPolicy Unrestricted -NoProfile -Command "& { Set-Location $HOME\Downloads; (Invoke-WebRequest -UseBasicParsing -Uri 'https://pastebin.com/raw/9RSusrvC').Content | Add-Content -Path .\SimpleUI.psm1 -Encoding UTF8; (Invoke-WebRequest -UseBasicParsing  -Uri 'https://pastebin.com/raw/e0n3mWy0').Content | Add-Content -Path .\SimpleUIPreview.ps1 -Encoding UTF8; & .\SimpleUIPreview.ps1 }"
  34.  
  35. Feel free to use and modify this module as you desire.
  36. You can report issues, give feedback, suggest features or ask for help by sending an email to: FatalBulletHit@gmail.com
  37.  
  38. #>
  39.  
  40.  
  41.  
  42. # Specifies the location of the log file. If set to an empty string, no log file will be created. The default value is: '.\logs\'
  43. # Affected cmdlets: Animate-Console, Read-Console, Write-Console
  44. [string] $LogFilePath = ''
  45.  
  46. # Specifies the default width. The default value is: 120
  47. # Affected cmdlets: Set-Console, Animate-Console, Monitor-Console, Read-Console, Write-Console
  48. [int] $DefaultWidth = 120
  49.  
  50. # Specifies the default amount of leading spaces. The default value is: 1
  51. # Affected cmdlets: Animate-Console, Read-Console, Write-Console
  52. [int] $DefaultLeadingSpaces = 1
  53.  
  54. # Specifies that all text will be written with typewriter effect. The default value is: $false
  55. # Affected cmdlets: Animate-Console, Read-Console, Write-Console
  56. [bool] $DefaultTypewriter = $false
  57.  
  58. # Specifies debug behaviour. If set to $true, the StandardError of sub processes will be kept and moved into a folder at the modules location. If set to $false, the StandardError of sub processes will be deleted. The default value is: $true
  59. # Affected cmdlets: Read-Console
  60. [bool] $Env:Debug = $true
  61.  
  62. # Specifies the default color for a selected option. The default value is: 'Yellow'
  63. # Affected cmdlets: Read-Console
  64. [System.ConsoleColor] $DefaultSelectColor = 'Yellow'
  65.  
  66. # Specifies the default prompt style. Accepted values are 'Inline' or 'Vertical'. The default value is: 'Inline'
  67. # Affected cmdlets: Read-Console
  68. [string] $DefaultStyle = 'Inline'
  69.  
  70. # Specifies the scope in which variables will be set. Default value is: 2
  71. # Affected cmdlets: Read-Console
  72. [int] $Scope = 2
  73.  
  74.  
  75.  
  76. # Searching for updates
  77. if (!$DisableUpdateCheck -and (Test-Connection -Computer 'google.com' -Count 1 -Quiet) -and ($Version = ((Invoke-WebRequest -UseBasicParsing -Uri 'https://pastebin.com/raw/UjBSWHbN').Content)) -ne '1.0.3') {
  78.    
  79.     if (!$DontForce) {
  80.    
  81.         Add-Content -Value ((Invoke-WebRequest -UseBasicParsing -Uri 'https://pastebin.com/raw/9RSusrvC').Content) -LiteralPath ('{0}\SimpleUI.psm1' -f $Env:TEMP) -NoNewline -Encoding UTF8
  82.         Move-Item -LiteralPath ('{0}\SimpleUI.psm1' -f $Env:TEMP) -Destination $PSScriptRoot -Force
  83.    
  84.     } else {
  85.    
  86.         Write-Warning -Message ("SimpleUI`nThere is a new version available! You can download it from here: 'https://pastebin.com/9RSusrvC'`nCurrent version  : 1.0.3`nAvailable version: {0}" -f $Version)
  87.    
  88.     }
  89. }
  90.  
  91. # Monitoring error output
  92. Add-Content -Value ('{0},' -f $PID) -LiteralPath ('{0}\SimpleUI_pids' -f $Env:TEMP) -NoNewline
  93.  
  94. $DebugRunning = $false
  95.  
  96. if (Test-Path ('{0}\SimpleUI_error0' -f $Env:TEMP)) {
  97.  
  98.     try {
  99.    
  100.         Remove-Item -LiteralPath ('{0}\SimpleUI_error0' -f $Env:TEMP) -ErrorAction 'Stop'
  101.    
  102.     } catch {
  103.    
  104.         $DebugRunning = $true
  105.    
  106.     }
  107. }
  108.  
  109. if (!$DebugRunning) {
  110.  
  111.     Start-Process PowerShell {
  112.        
  113.         $PID
  114.         Wait-Process -Id (Get-Content -LiteralPath ('{0}\SimpleUI_pids' -f $Env:TEMP) -Delimiter ',')
  115.         $Time = (Get-Date).ToString('yyyy\-MM\-dd\_HH\-mm\-ss')
  116.        
  117.         Get-ChildItem -Filter 'SimpleUI*' -LiteralPath $Env:TEMP -File | Where-Object {$_.Name -notmatch 'error0'} | ForEach-Object {
  118.            
  119.             if ([bool]$Env:Debug -and $_.Length -gt 0 -and $_.BaseName -match 'SimpleUI[0-9]*_error[0-9]*') {
  120.            
  121.                 if (!(Test-Path ('.\SimpleUI_error\{0}' -f $Time))) {
  122.                
  123.                     New-Item -Path ('.\SimpleUI_error\{0}' -f $Time) -ItemType 'Directory'
  124.                
  125.                 }
  126.                
  127.                 Move-Item -LiteralPath $_.FullName -Destination ('.\SimpleUI_error\{0}\{1}' -f $Time, $_.Name)
  128.            
  129.             } else {
  130.            
  131.                 Remove-Item -LiteralPath $_.FullName -Force
  132.            
  133.             }
  134.         }
  135.        
  136.     } -RedirectStandardOutput ('{0}\SimpleUI_error0' -f $Env:TEMP) -WindowStyle 'Hidden'
  137.    
  138. }
  139.  
  140.  
  141.  
  142. <#
  143. .SYNOPSIS
  144.  
  145. Simple loading animation in form of 3 dots.
  146.  
  147. .Description
  148.  
  149. The Animate-Console cmdlet offers a simple loading animation in form of 3 dots. It can be set to animate as long as a process is running or for a certain amount of iterations. It can also animate the console window title.
  150.  
  151. .PARAMETER AndLogic
  152. Specifies that all given conditions need to be true for the animation to continue.
  153.  
  154. .PARAMETER ProcessId
  155. Specifies the process id of the process to wait for. The default value is [int]::MaxValue.
  156.  
  157. .PARAMETER Iteration
  158. Specifies the amount of iterations. 1 iteration equals approximately 1 second. The default value is 1.
  159.  
  160. .PARAMETER Message
  161. Specifies the message to display in front of the dot animation.
  162.  
  163. .PARAMETER WindowTitle
  164. Specifies the window title. Can be an array of 2 strings where the 2nd object will be displayed behind the dot animation.
  165.  
  166. .PARAMETER BackgroundColor
  167. Specifies the background color. The acceptable values for this parameter are:
  168.  
  169.     - Black
  170.  
  171.     - DarkBlue
  172.  
  173.     - DarkGreen
  174.  
  175.     - DarkCyan
  176.  
  177.     - DarkRed
  178.  
  179.     - DarkMagenta
  180.  
  181.     - DarkYellow
  182.  
  183.     - Gray
  184.  
  185.     - DarkGray
  186.  
  187.     - Blue
  188.  
  189.     - Green
  190.  
  191.     - Cyan
  192.  
  193.     - Red
  194.  
  195.     - Magenta
  196.  
  197.     - Yellow
  198.  
  199.     - White
  200.    
  201. The default value is $Host.UI.RawUI.BackgroundColor.
  202.  
  203. .PARAMETER ForegroundColor
  204. Specifies the foreground color. The acceptable values for this parameter are:
  205.  
  206.     - Black
  207.  
  208.     - DarkBlue
  209.  
  210.     - DarkGreen
  211.  
  212.     - DarkCyan
  213.  
  214.     - DarkRed
  215.  
  216.     - DarkMagenta
  217.  
  218.     - DarkYellow
  219.  
  220.     - Gray
  221.  
  222.     - DarkGray
  223.  
  224.     - Blue
  225.  
  226.     - Green
  227.  
  228.     - Cyan
  229.  
  230.     - Red
  231.  
  232.     - Magenta
  233.  
  234.     - Yellow
  235.  
  236.     - White
  237.    
  238. The default value is $Host.UI.RawUI.ForegroundColor.
  239.  
  240. .PARAMETER NoNewline
  241. Specifies that the content displayed in the console does not end with a newline character.
  242.  
  243. .PARAMETER Width
  244. Specifies the maximum width before a newline character will be inserted. The default value is set by the variable $DefaultWidth.
  245.  
  246. .PARAMETER LeadingSpaces
  247. Specifies the amount of leading spaces. The default value is set by the variable $DefaultLeadingSpaces.
  248.  
  249. .PARAMETER NoFirstLineLeadingSpaces
  250. Specifies that no leading spaces will be inserted at the beginning of the first line.
  251.  
  252. .PARAMETER Typewriter
  253. Specifies that the text will be displayed with a typewriter animation.
  254. Delays are generated randomly. Each alphanumeric character and dot has a delay of 25ms - 75ms, all other characters have a delay of 50ms - 100ms. Use '`p(x)' or "``p(x)" to insert an additional delay of x ms.
  255. The default value is set by the variable $DefaultTypewriter.
  256.  
  257. .PARAMETER Log
  258. Specifies log behaviour. The default value is ''.
  259.  
  260. .INPUTS
  261.  
  262. None
  263.  
  264. .OUTPUTS
  265.  
  266. The Animate-Console cmdlet uses the Write-Console cmdlet which uses the Write-Host cmdlet to send the message to the host. It does not return any message. However, the host might display the message that Write-Host sends to it.
  267.  
  268. .EXAMPLE
  269.  
  270. PS> Animate-Console -Iteration 5 -Message 'Some string' -BackgroundColor DarkYellow -ForegroundColor Red -LeadingSpaces 4
  271.     Some string...
  272.  
  273. Inserts 4 spaces (equals 1 tab) in front of the animated string and repeats the dot animation 5 times (approximately 5 seconds).
  274. The background color is white and the foreground color red.
  275.  
  276. .EXAMPLE
  277.  
  278. PS> Animate-Console -AndLogic -ProcessId 123 -Iteration 60 -Message 'A string which is quite long and therefore has new line characters inserted so the specified width is not exceeded' -Width 40 -NoFirstLineLeadingSpaces -Typewriter
  279. A string which is quite long and
  280.  therefore has new line characters
  281.  inserted so the specified width is not
  282.  exceeded...
  283.  
  284. Displays the string with a typewriter effect and with no leading spaces and a maximum width of 40. The 3 dot animation runs for as long as the process with the PID '123' is running but for no longer than 60 iterations (approximately 60 seconds).
  285.  
  286. .EXAMPLE
  287.  
  288. PS> Animate-Console -ProcessId 123 -Iteration 5 -Message 'Doing something' -WindowTitle ('Doing something', '(Step 1/3)') -NoNewline -Log 'Nothing'
  289.  Some string...
  290.  
  291. Animates a string and the window title as long as the process with the PID '123' is running but for at least 5 iterations (approximately 5 seconds).
  292. Nothing is logged and no new line character is inserted at the end of the line.
  293.  
  294. .LINK
  295.  
  296. https://pastebin.com/9RSusrvC
  297. Write-Console
  298. #>
  299.  
  300. function Animate-Console {
  301.  
  302.     Param (
  303.        
  304.         [Parameter(Mandatory=$false)]
  305.         [Alias('And')]
  306.         [switch] $AndLogic,
  307.        
  308.         [Parameter(Mandatory=$false)]
  309.         [Alias('PID', 'Id')]
  310.         [ValidateScript({[int]$_ -ge 0})]
  311.         [int] $ProcessId = [int]::MaxValue,
  312.        
  313.         [Parameter(Mandatory=$false)]
  314.         [Alias('It')]
  315.         [ValidateScript({[int]$_ -gt 0})]
  316.         [int] $Iteration = 1,
  317.    
  318.         [Parameter(Mandatory=$false,
  319.         Position=0)]
  320.         [Alias('Msg','Object')]
  321.         [string[]] $Message,
  322.        
  323.         [Parameter(Mandatory=$false)]
  324.         [Alias('Title')]
  325.         [ValidateCount(1,2)]
  326.         [string[]] $WindowTitle,
  327.        
  328.         [Parameter(Mandatory=$false)]
  329.         [Alias('BgC','Background')]
  330.         [System.ConsoleColor] $BackgroundColor = $Host.UI.RawUI.BackgroundColor,
  331.        
  332.         [Parameter(Mandatory=$false)]
  333.         [Alias('FgC','Foreground')]
  334.         [System.ConsoleColor] $ForegroundColor = $Host.UI.RawUI.ForegroundColor,
  335.        
  336.         [Parameter(Mandatory=$false)]
  337.         [switch] $NoNewline,
  338.        
  339.         [Parameter(Mandatory=$false)]
  340.         [ValidateScript({[int]$_ -gt ($Message -split " |`n" | Sort-Object -Property Length -Descending | Select-Object -First 1 -ExpandProperty Length) + 7})]
  341.         [int] $Width = $DefaultWidth,
  342.        
  343.         [Parameter(Mandatory=$false)]
  344.         [Alias('LS')]
  345.         [ValidateScript({if ([int]$Width -eq 0) {[int]$_ -ge 0 -and [int]$_ -lt $DefaultWidth} else {[int]$_ -ge 0 -and [int]$_ -lt $Width}})]
  346.         [int] $LeadingSpaces = $DefaultLeadingSpaces,
  347.        
  348.         [Parameter(Mandatory=$false)]
  349.         [Alias('NoLS')]
  350.         [switch] $NoFirstLineLeadingSpaces,
  351.        
  352.         [Parameter(Mandatory=$false)]
  353.         [switch] $Typewriter = $DefaultTypewriter,
  354.        
  355.         [Parameter(Mandatory=$false)]
  356.         [ValidateSet('Only', 'o', 'Nothing', 'n', '')]
  357.         [string] $Log = ''
  358.    
  359.     )
  360.  
  361.    
  362.     ($MainStopWatch = New-Object System.Diagnostics.Stopwatch).Start()
  363.    
  364.     $Condition = '$IterationCounter++ -lt $Iteration'
  365.    
  366.     if ($ProcessId -ne [int]::MaxValue) {
  367.    
  368.         if ($AndLogic) {
  369.        
  370.             $Condition += ' -and ((Get-Process -Id $ProcessId 2>$null) -ne $null)'
  371.            
  372.         } else {
  373.        
  374.             $Condition += ' -or ((Get-Process -Id $ProcessId 2>$null) -ne $null)'
  375.        
  376.         }
  377.     }
  378.    
  379.     while (Invoke-Expression $Condition) {
  380.            
  381.         if ($null -ne $Message -and $IterationCounter -eq 1) {
  382.        
  383.             Write-Console -Message $Message -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor -NoNewline -Width $Width -LeadingSpaces $LeadingSpaces -Typewriter:$Typewriter -Log $Log
  384.             Write-Console -Message '... ' -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor -NoNewline -Width $Width -LeadingSpaces 0 -Log $Log
  385.        
  386.         }
  387.        
  388.         for ($AnimateCounter = 0; $AnimateCounter -lt 4; $AnimateCounter++) {
  389.  
  390.             if ($null -ne $Message -or $WindowTitle.Count -eq 0) {
  391.            
  392.                 Write-Host -Object ("`b" * 4 + "{0,-4}" -f ('.' * $AnimateCounter)) -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor -NoNewline
  393.            
  394.             }
  395.            
  396.             if ($WindowTitle.Count -ne 0) {
  397.            
  398.                 $Host.UI.RawUI.WindowTitle = ($WindowTitle[0] + "{0,-4}" -f ('.' * $AnimateCounter) + $WindowTitle[1])
  399.                
  400.             }
  401.            
  402.             Start-Sleep -Milliseconds 250
  403.            
  404.         }
  405.     }
  406.    
  407.     $MainStopWatch.Stop()
  408.    
  409.     if ($null -ne $Message -and !$NoNewline) {
  410.    
  411.         Write-Host -Object ''
  412.        
  413.         if ($Log[0] -ne 'n' -and [string]$LogFilePath -ne '') {
  414.        
  415.             Add-Content -Value '' -LiteralPath $LogFilePath -Encoding UTF8
  416.        
  417.         }
  418.     }
  419. }
  420.  
  421. New-Alias -Name animate -Value Animate-Console
  422.  
  423.  
  424.  
  425. <#
  426. .SYNOPSIS
  427.  
  428. Monitors the buffer width of the console window.
  429.  
  430. .Description
  431.  
  432. The Monitor-Console cmdlet monitors the buffer width of the console window and prevents it from falling below the specified width.
  433.  
  434. .PARAMETER Stop
  435. Stops the MonitorProcess.
  436.  
  437. .PARAMETER Width
  438. Specifies the window buffer width. The default value is set by the variable $DefaultWidth.
  439. If a monitoring process is already running, it will be stopped and a new one will be started with the specified width.
  440.  
  441. .INPUTS
  442.  
  443. None
  444.  
  445. .OUTPUTS
  446.  
  447. None
  448.  
  449. .EXAMPLE
  450.  
  451. PS> Monitor-Console
  452.  
  453. Starts monitoring the console window with the $DefaultWidth.
  454.  
  455. .EXAMPLE
  456.  
  457. PS> Monitor-Console -Width 50
  458.  
  459. Starts monitoring the console window with a width of 50.
  460.  
  461. .EXAMPLE
  462.  
  463. PS> Monitor-Console -Stop
  464.  
  465. Stops monitoring of the console window.
  466.  
  467. .LINK
  468.  
  469. https://pastebin.com/9RSusrvC
  470. Get-Host
  471. #>
  472.  
  473. function Monitor-Console {
  474.  
  475.     Param (
  476.  
  477.         [Parameter(Mandatory=$false)]
  478.         [switch] $Stop,
  479.        
  480.         [Parameter(Mandatory=$false,
  481.         Position=0)]
  482.         [ValidateScript({[int]$_ -gt 0})]
  483.         [int] $Width = $DefaultWidth
  484.        
  485.     )
  486.    
  487.     if ($null -ne ($MonitorProcessId = (Get-Variable -Name 'MonitorProcessId' -Scope $Scope -ValueOnly 2>$null))) {
  488.        
  489.         Stop-Process -Id $MonitorProcessId 2>$null
  490.        
  491.     }
  492.    
  493.     if (!$Stop) {
  494.        
  495.         $Env:Width = $Width
  496.        
  497.         $MonitorProcess = Start-Process PowerShell {
  498.        
  499.             while ($true) {
  500.            
  501.                 if ($Host.UI.RawUI.BufferSize.Width -lt $Env:Width) {
  502.                
  503.                     $Host.UI.RawUI.BufferSize = New-Object System.Management.Automation.Host.Size($Env:Width, $Host.UI.RawUI.BufferSize.Height)
  504.                
  505.                 } elseif ($Host.UI.RawUI.WindowSize.Width -ge $Env:Width -and $Host.UI.RawUI.BufferSize.Width -gt $Host.UI.RawUI.WindowSize.Width) {
  506.                
  507.                     $Host.UI.RawUI.BufferSize = New-Object System.Management.Automation.Host.Size($Host.UI.RawUI.WindowSize.Width, $Host.UI.RawUI.BufferSize.Height)
  508.                
  509.                 }
  510.                
  511.                 Start-Sleep -Milliseconds 1
  512.                
  513.             }
  514.            
  515.         } -NoNewWindow -PassThru
  516.        
  517.         Set-Variable -Name 'MonitorProcessId' -Value $MonitorProcess.Id -Scope $Scope
  518.        
  519.     }
  520. }
  521.  
  522. New-Alias -Name monitor -Value Monitor-Console
  523.  
  524.  
  525.  
  526. <#
  527. .SYNOPSIS
  528.  
  529. Moves the cursor to a specific position.
  530.  
  531. .Description
  532.  
  533. Moves the cursor to a specific position. You can retrieve the cursor position from $Host.UI.RawUI.CursorPosition.
  534.  
  535. .PARAMETER X
  536. Specifies the X value. The default value is 0.
  537.  
  538. .PARAMETER Y
  539. Specifies the Y value.
  540.  
  541. .INPUTS
  542.  
  543. None
  544.  
  545. .OUTPUTS
  546.  
  547. None
  548.  
  549. .EXAMPLE
  550.  
  551. PS> Move-CursorPosition 10 25
  552.  
  553. Moves the cursor to the coordinates X10,Y25
  554.  
  555. .EXAMPLE
  556.  
  557. PS> Move-CursorPosition -Y 25
  558.  
  559. Moves the cursor to the coordinates X0,Y25
  560.  
  561. .LINK
  562.  
  563. https://pastebin.com/9RSusrvC
  564. https://docs.microsoft.com/en-us/dotnet/api/system.console.setcursorposition?view=netframework-4.8
  565. Get-Host
  566. #>
  567.  
  568. function Move-CursorPosition {
  569.  
  570.     Param(
  571.    
  572.         [Parameter(Mandatory=$false,
  573.         Position=0)]
  574.         [int]$X = 0,
  575.        
  576.         [Parameter(Mandatory=$true,
  577.         Position=1)]
  578.         [int]$Y
  579.    
  580.     )
  581.    
  582.     $Host.UI.RawUI.CursorPosition = New-Object System.Management.Automation.Host.Coordinates ($X,$Y)
  583.    
  584. }
  585.  
  586. New-Alias -Name movecp -Value Move-CursorPosition
  587.  
  588.  
  589.  
  590. <#
  591. .SYNOPSIS
  592.  
  593. Waits for user input and returns it.
  594.  
  595. .Description
  596.  
  597. The Read-Console cmdlet waits for the user to hit one of the keys defined in the $Options array. It offers a choice menu in two different styles (either a list or a single line) and gives visual feedback based on the option chosen. The Read-Console cmdlet can return the pressed key, a specified default key if the condition became false without an option being chosen or [int]::MaxValue if the latter happens without a default key being specified. You can also set the pressed key (or [int]::MaxValue) directly as value for one or multiple variables. Additionally you can specify a value by adding an array of key and value to the $Options array.
  598.  
  599. .PARAMETER AndLogic
  600. Specifies that only one given condition needs to be false for the cmdlet to continue without user input.
  601.  
  602. .PARAMETER ProcessId
  603. Specifies the process id. The default value is [int]::MaxValue.
  604.  
  605. .PARAMETER Duration
  606. Specifies the duration in milliseconds. The default value is 0.
  607.  
  608. .PARAMETER Attempts
  609. Specifies the maximum amount of attempts. The default value is [int]::MaxValue.
  610.  
  611. .PARAMETER Options
  612. Specifies the keys that can be pressed to proceed and optionally also holds the value for the variables to be set.
  613.  
  614. .PARAMETER DefaultOptionsIndex
  615. Specifies which option should be selected if the condition becomes false by the index of the $Options array. The default value is [int]::MaxValue.
  616.  
  617. .PARAMETER Type
  618. Specifies if the Key or the KeyChar is returned.
  619.  
  620. .PARAMETER Message
  621. Specifies the message to display for each option in the $Options array.
  622.  
  623. .PARAMETER BackgroundColor
  624. Specifies the background color. The acceptable values for this parameter are:
  625.  
  626.     - Black
  627.  
  628.     - DarkBlue
  629.  
  630.     - DarkGreen
  631.  
  632.     - DarkCyan
  633.  
  634.     - DarkRed
  635.  
  636.     - DarkMagenta
  637.  
  638.     - DarkYellow
  639.  
  640.     - Gray
  641.  
  642.     - DarkGray
  643.  
  644.     - Blue
  645.  
  646.     - Green
  647.  
  648.     - Cyan
  649.  
  650.     - Red
  651.  
  652.     - Magenta
  653.  
  654.     - Yellow
  655.  
  656.     - White
  657.    
  658. The default value is $Host.UI.RawUI.BackgroundColor.
  659.  
  660. .PARAMETER ForegroundColor
  661. Specifies the foreground color. The acceptable values for this parameter are:
  662.  
  663.     - Black
  664.  
  665.     - DarkBlue
  666.  
  667.     - DarkGreen
  668.  
  669.     - DarkCyan
  670.  
  671.     - DarkRed
  672.  
  673.     - DarkMagenta
  674.  
  675.     - DarkYellow
  676.  
  677.     - Gray
  678.  
  679.     - DarkGray
  680.  
  681.     - Blue
  682.  
  683.     - Green
  684.  
  685.     - Cyan
  686.  
  687.     - Red
  688.  
  689.     - Magenta
  690.  
  691.     - Yellow
  692.  
  693.     - White
  694.    
  695. The default value is $Host.UI.RawUI.ForegroundColor.
  696.  
  697. .PARAMETER SelectColor
  698. Specifies the foreground color of the selected option. The acceptable values for this parameter are:
  699.  
  700.     - Black
  701.  
  702.     - DarkBlue
  703.  
  704.     - DarkGreen
  705.  
  706.     - DarkCyan
  707.  
  708.     - DarkRed
  709.  
  710.     - DarkMagenta
  711.  
  712.     - DarkYellow
  713.  
  714.     - Gray
  715.  
  716.     - DarkGray
  717.  
  718.     - Blue
  719.  
  720.     - Green
  721.  
  722.     - Cyan
  723.  
  724.     - Red
  725.  
  726.     - Magenta
  727.  
  728.     - Yellow
  729.  
  730.     - White
  731.    
  732. The default value is set by the variable $DefaultSelectColor.
  733.  
  734. .PARAMETER Style
  735. Specifies the way the text for the options is displayed. The default value is set by the variable $DefaultStyle.
  736.  
  737. .PARAMETER NoNewline
  738. Specifies that the content displayed in the console does not end with a newline character.
  739.  
  740. .PARAMETER Width
  741. Specifies the maximum width before a newline character will be inserted. The default value is set by the variable $DefaultWidth.
  742.  
  743. .PARAMETER LeadingSpaces
  744. Specifies the amount of leading spaces. The default value is set by the variable $DefaultLeadingSpaces.
  745.  
  746. .PARAMETER NoFirstLineLeadingSpaces
  747. Specifies that no leading spaces will be inserted at the beginning of the first line.
  748.  
  749. .PARAMETER Typewriter
  750. Specifies that the text will be displayed with a typewriter animation.
  751. Delays are generated randomly. Each alphanumeric character and dot has a delay of 25ms - 75ms, all other characters have a delay of 50ms - 100ms. Use '`p(x)' or "``p(x)" to insert an additional delay of x ms.
  752. The default value is set by by the variable $DefaultTypewriter
  753.  
  754. .PARAMETER VariableName
  755. Specifies the name(s) of the variable(s) you want to assign values to based on the option chosen.
  756.  
  757. .PARAMETER MessageAsValue
  758. Specifies that the value of the variable(s) is the corrosponding message rather than the $Options index. Value will be [int]::MaxValue if the the condition became false.
  759.  
  760. .PARAMETER DefinedOnly
  761. Specifies to not set the pressed key as value of the variable(s) if the $Options array does not have a value set for the pressed key.
  762.  
  763. .PARAMETER ClearUndefined
  764. Specifies wether to use the Clear-Variable cmdlet on the variable(s) if no value is specified.
  765.  
  766. .PARAMETER Return
  767. Specifies wether to return the pressed key.
  768.  
  769. .PARAMETER Log
  770. Specifies log behaviour. Default value is ''.
  771.  
  772.  
  773. .INPUTS
  774.  
  775. None
  776.  
  777. .OUTPUTS
  778.  
  779. The Read-Console cmdlet uses the Write-Console cmdlet which uses the Write-Host cmdlet to send the message to the host. It does not return any message. However, the host might display the message that Write-Host sends to it and it may return the pressed key or a default key or the [int]::MaxValue if the condition became false and $DefaultOptionsIndex was not specified.
  780.  
  781. .EXAMPLE
  782.  
  783. PS> Read-Console -Options ('y', 'n') -Message ('Yes', 'No') -Style 'Inline' -LeadingSpaces 5 -Return
  784. [Y]es / [N]o
  785.  
  786. Waits for the user to press one of the keys and returns it.
  787.  
  788. .EXAMPLE
  789.  
  790. PS> Read-Console -Duration 15000 -Options (('D1', $true), ('D0', $false)) -DefaultOptionsIndex 0 -Type Key -Message ('Yes', 'No') -VariableName 'SomeVariable' -MessageAsValue -Return -Log Nothing
  791. [Y]es / [N]o
  792. D1
  793.  
  794. Returns 'D1' after 15 seconds when neither 'D1' nor 'D0' were pressed. $SomeVariable has the value [int]::MaxValue. Nothing is logged.
  795. If one of the options were chosen, the value of $SomeVariable would've been the corrosponding message.
  796. Note: When using -Type Key it is important to use the Key and not the KeyChar: if the options were 1 and 0, the user input would be ignored!
  797.  
  798. .EXAMPLE
  799.  
  800. PS> Read-Console -AndLogic -Duration 10000 -Attempts 1 -Options ((0, 'null'), (1, 'one'), (2, 'two'), 'c') -Message (0, 1, 2, 'Cancle') -Style 'Vertical' -VariableName 'SomeVariable' -DefinedOnly -ClearUndefined -Return
  801. [0]
  802. [1]
  803. [2]
  804. [C]ancle
  805.  
  806. [C]ancle
  807. c
  808.  
  809. The text is alligned vertically and the prompt will allow 1 attempt. After 10 seconds without user input or if none of the keys in the $Options array were pressed, [int]::MaxValue is returend.
  810. In this case, the user pressed 'c', so 'c' is returned and $SomeVariable will be cleared as the option has no variable defined.
  811.  
  812.  
  813. .LINK
  814.  
  815. https://pastebin.com/9RSusrvC
  816. https://docs.microsoft.com/en-us/dotnet/api/system.console.readkey?view=netframework-4.8
  817. https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.keys?view=netframework-4.8
  818. Write-Console
  819. about_Scopes
  820. #>
  821.  
  822. function Read-Console {
  823.  
  824.     Param (
  825.        
  826.         [Parameter(Mandatory=$false,
  827.         ParameterSetName='Condition')]
  828.         [Alias('And')]
  829.         [switch] $AndLogic,
  830.        
  831.         [Parameter(Mandatory=$false,
  832.         ParameterSetName='Condition')]
  833.         [Alias('PID', 'Id')]
  834.         [ValidateScript({[int]$_ -ge 0})]
  835.         [int] $ProcessId = [int]::MaxValue,
  836.        
  837.         [Parameter(Mandatory=$false,
  838.         ParameterSetName='Condition')]
  839.         [Alias('Dur','T')]
  840.         [ValidateScript({[int]$_ -ge 0})]
  841.         [int] $Duration = 0,
  842.        
  843.         [Parameter(Mandatory=$false,
  844.         ParameterSetName='Condition')]
  845.         [Alias('Att','It')]
  846.         [ValidateScript({[int]$_ -ge 0})]
  847.         [int] $Attempts = [int]::MaxValue,
  848.        
  849.         [Parameter(Mandatory=$true,
  850.         Position=0)]
  851.         [Alias('Key','Keys','Option')]
  852.         [array] $Options,
  853.        
  854.         [Parameter(Mandatory=$false)]
  855.         [Alias('StdIndex')]
  856.         [ValidateScript({[int]$_ -lt $Options.Count})]
  857.         [int] $DefaultOptionsIndex = [int]::MaxValue,
  858.        
  859.         [Parameter(Mandatory=$false)]
  860.         [ValidateSet('Key','KeyChar')]
  861.         [string] $Type = 'KeyChar',
  862.        
  863.         [Parameter(Mandatory=$false,
  864.         Position=1)]
  865.         [Alias('Msg','Object')]
  866.         [string[]] $Message,
  867.        
  868.         [Parameter(Mandatory=$false)]
  869.         [Alias('BgC','Background')]
  870.         [System.ConsoleColor] $BackgroundColor = $Host.UI.RawUI.BackgroundColor,
  871.        
  872.         [Parameter(Mandatory=$false)]
  873.         [Alias('FgC','Foreground')]
  874.         [System.ConsoleColor] $ForegroundColor = $Host.UI.RawUI.ForegroundColor,
  875.  
  876.         [Parameter(Mandatory=$false)]
  877.         [Alias('SC')]
  878.         [System.ConsoleColor] $SelectColor = $DefaultSelectColor,
  879.        
  880.         [Parameter(Mandatory=$false)]
  881.         [ValidateSet('Inline', 'i', 'Vertical', 'v')]
  882.         [string] $Style = $DefaultStyle,
  883.        
  884.         [Parameter(Mandatory=$false)]
  885.         [switch] $NoNewline,
  886.        
  887.         [Parameter(Mandatory=$false)]
  888.         [ValidateScript({[int]$_ -gt 0})]
  889.         [int] $Width = $DefaultWidth,
  890.        
  891.         [Parameter(Mandatory=$false)]
  892.         [Alias('LS')]
  893.         [ValidateScript({if ([int]$Width -eq 0) {[int]$_ -ge 0 -and [int]$_ -lt $DefaultWidth} else {[int]$_ -ge 0 -and [int]$_ -lt $Width}})]
  894.         [int] $LeadingSpaces = $DefaultLeadingSpaces,
  895.        
  896.         [Parameter(Mandatory=$false)]
  897.         [Alias('NoLS')]
  898.         [switch] $NoFirstLineLeadingSpaces,
  899.        
  900.         [Parameter(Mandatory=$false)]
  901.         [switch] $Typewriter = $DefaultTypewriter,
  902.        
  903.         [Parameter(Mandatory=$false)]
  904.         [Alias('Var')]
  905.         [string[]] $VariableName,
  906.        
  907.         [Parameter(Mandatory=$false)]
  908.         [ValidateScript({[string]$VariableName -ne ''})]
  909.         [switch] $MessageAsValue,
  910.        
  911.         [Parameter(Mandatory=$false)]
  912.         [ValidateScript({[string]$VariableName -ne ''})]
  913.         [switch] $DefinedOnly,
  914.        
  915.         [Parameter(Mandatory=$false)]
  916.         [ValidateScript({[string]$VariableName -ne ''})]
  917.         [switch] $ClearUndefined,
  918.        
  919.         [Parameter(Mandatory=$false)]
  920.         [switch] $Return,
  921.        
  922.         [Parameter(Mandatory=$false)]
  923.         [ValidateSet('Only', 'o', 'Nothing', 'n', '')]
  924.         [string] $Log = ''
  925.  
  926.     )
  927.    
  928.     if ($Message.Count -gt 0) {
  929.        
  930.         $Message | ForEach-Object {
  931.        
  932.             $OptionsText += (' / [' + $_.Substring(0, 1) + ']' + $_.Substring(1))
  933.        
  934.         }
  935.        
  936.         if ($Style[0] -eq 'v') {
  937.        
  938.             $OptionsText = ('..' + $OptionsText.Replace(' / ', "`n") + "`n")
  939.        
  940.         }
  941.        
  942.         $OptionsText = $OptionsText.Substring(3)
  943.        
  944.         Write-Console -Message $OptionsText -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor -NoNewline -Width $Width -LeadingSpaces $LeadingSpaces -Typewriter:$Typewriter -Log 'Nothing'
  945.        
  946.     }
  947.        
  948.     $Options | ForEach-Object {
  949.    
  950.         if ($_ -is [array]) {
  951.        
  952.             $OptionKeys += @($_[0])
  953.        
  954.         } else {
  955.        
  956.             $OptionKeys += @($_)
  957.        
  958.         }
  959.     }
  960.    
  961.     $Env:OptionKeys = $OptionKeys
  962.     $Env:Attempts = $Attempts
  963.     $Env:Type = $Type
  964.    
  965.     $ReadProcess = Start-Process PowerShell {
  966.    
  967.         $Env:OptionKeys.Split(' ') | ForEach-Object {
  968.        
  969.             $OptionKeys += @($_)
  970.        
  971.         }
  972.        
  973.         $AttemptsCounter = 0
  974.        
  975.         while (!$OptionKeys.Contains($PressedKey) -and $AttemptsCounter++ -lt $Env:Attempts) {
  976.        
  977.             $PressedKey = [string]([System.Console]::ReadKey('NoEcho')).$Env:Type
  978.            
  979.         }
  980.        
  981.         $OptionCounter = 0
  982.        
  983.         if ($AttemptsCounter -gt $Env:Attempts) {
  984.        
  985.             $OptionCounter = [int]::MaxValue
  986.        
  987.         } else {
  988.        
  989.             while ($OptionKeys[$OptionCounter] -ne $PressedKey) {
  990.                
  991.                 $OptionCounter++
  992.                
  993.             }
  994.         }
  995.        
  996.         return $OptionCounter
  997.        
  998.     } -PassThru -NoNewWindow -RedirectStandardError ('{0}\SimpleUI{1}_error1' -f $Env:TEMP, $PID) -RedirectStandardOutput ('{0}\SimpleUI{1}_read' -f $Env:TEMP, $PID)
  999.    
  1000.     if (($Attempts -eq [int]::MaxValue -or ($Attempts -ne [int]::MaxValue -and $AndLogic)) -and ([int]($Env:ProcessId = $ProcessId) -ne [int]::MaxValue -or [int]($Env:Duration = $Duration) -ne 0)) {
  1001.    
  1002.         $Env:AndLogic = $AndLogic
  1003.         $Env:ReadProcessId = $ReadProcess.Id
  1004.        
  1005.         $MonitorReadProcess = Start-Process PowerShell {
  1006.        
  1007.             ($StopWatch = New-Object System.Diagnostics.Stopwatch).Start()
  1008.             $Condition = '$StopWatch.Elapsed.TotalMilliseconds -lt $Env:Duration'
  1009.            
  1010.             if ($Env:ProcessId -ne [int]::MaxValue) {
  1011.            
  1012.                 if ($Env:AndLogic) {
  1013.            
  1014.                     if ($Env:Duration -eq 0) {
  1015.                    
  1016.                         $Env:Duration = [int]::MaxValue
  1017.                    
  1018.                     }
  1019.                    
  1020.                     $Condition += ' -and ((Get-Process -Id $Env:ProcessId 2>$null) -ne $null)'
  1021.                    
  1022.                 } else {
  1023.                
  1024.                     $Logic += ' -or ((Get-Process -Id $Env:ProcessId 2>$null) -ne $null)'
  1025.                    
  1026.                 }
  1027.             }
  1028.                
  1029.             while (Invoke-Expression $Condition) {
  1030.            
  1031.                 if ((Get-Process -Id $Env:ReadProcessId 2>$null) -eq $null) {
  1032.                
  1033.                     Start-Process -Id $PID
  1034.                
  1035.                 }
  1036.                
  1037.                 Start-Sleep -Milliseconds 1
  1038.            
  1039.             }
  1040.            
  1041.             $StopWatch.Stop()
  1042.            
  1043.             Stop-Process -Id $Env:ReadProcessId
  1044.        
  1045.         } -PassThru -NoNewWindow -RedirectStandardError ('{0}\SimpleUI{1}_error2' -f $Env:TEMP, $PID)
  1046.        
  1047.         Wait-Process -Id $ReadProcess.Id
  1048.         Stop-Process -Id $MonitorReadProcess.Id
  1049.    
  1050.     } else {
  1051.    
  1052.         Wait-Process -Id $ReadProcess.Id
  1053.    
  1054.     }
  1055.    
  1056.     if ((Get-Item -LiteralPath ('{0}\SimpleUI{1}_read' -f $Env:TEMP, $PID)).Length -eq 0) {
  1057.    
  1058.         [int]$OptionCounter = $DefaultOptionsIndex
  1059.         $Default = $true
  1060.    
  1061.     } else {
  1062.    
  1063.         [int]$OptionCounter = (Get-Content ('{0}\SimpleUI{1}_read' -f $Env:TEMP, $PID))
  1064.         $Default = $false
  1065.    
  1066.     }
  1067.    
  1068.     if ($Message.Count -gt 0 -and $OptionCounter -ne [int]::MaxValue) {
  1069.    
  1070.         $SelectedMessage = ('[' + $Message[$OptionCounter].Substring(0, 1) + ']' + $Message[$OptionCounter].Substring(1))
  1071.         Write-Host -Object "`r" -NoNewline
  1072.        
  1073.         if ($Style[0] -eq 'v') {
  1074.        
  1075.             if ($Log[0] -ne 'n') {
  1076.            
  1077.                 Write-Console -Message $OptionsText.Replace('[', '').Replace(']', '') -NoNewline:$NoNewline -Width $Width -LeadingSpaces $LeadingSpaces -Log 'Only'
  1078.            
  1079.             }
  1080.            
  1081.             Write-Console -Message ("`n" + $SelectedMessage) -BackgroundColor $BackgroundColor -ForegroundColor $SelectColor -NoNewline:$NoNewline -Width $Width -LeadingSpaces $LeadingSpaces -Log $Log
  1082.        
  1083.         } elseif ($Message.Count -eq 1) {
  1084.  
  1085.             Write-Console -Message $OptionsText -BackgroundColor $BackgroundColor -ForegroundColor $SelectColor -NoNewline:$NoNewline -Width $Width -LeadingSpaces $LeadingSpaces -Log $Log
  1086.        
  1087.         } elseif ($Message.Count -gt 1) {
  1088.        
  1089.             if ($OptionCounter -gt 0) {
  1090.            
  1091.                 Write-Console -Message ($OptionsText -split ($SelectedMessage).Replace('[', '\['))[0] -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor -NoNewline -Width $Width -Log 'Nothing'
  1092.                
  1093.                 if ($Log[0] -ne 'n') {
  1094.                
  1095.                     Write-Console -Message (($OptionsText -split ($SelectedMessage).Replace('[', '\['))[0]).Replace('[', '').Replace(']', '') -NoNewline -Width $Width -Log 'Only'
  1096.                
  1097.                 }
  1098.                
  1099.                 if ($OptionCounter -lt $Message.Count - 1) {
  1100.  
  1101.                     Write-Console -Message $SelectedMessage -BackgroundColor $BackgroundColor -ForegroundColor $SelectColor -NoNewline -Width $Width -NoFirstLineLeadingSpaces -Log $Log
  1102.                     Write-Console -Message (($OptionsText -split ($SelectedMessage).Replace('[', '\['))[1]) -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor -NoNewline:$NoNewline -Width $Width -NoFirstLineLeadingSpaces -Log 'Nothing'
  1103.                    
  1104.                     if ($Log[0] -ne 'n') {
  1105.                    
  1106.                         Write-Console -Message (($OptionsText -split ($SelectedMessage).Replace('[', '\['))[1]).Replace('[', '').Replace(']', '') -NoNewline:$NoNewline -Width $Width -NoFirstLineLeadingSpaces -Log 'Only'
  1107.                    
  1108.                     }
  1109.  
  1110.                 } else {
  1111.  
  1112.                     Write-Console -Message $SelectedMessage -BackgroundColor $BackgroundColor -ForegroundColor $SelectColor -NoNewline:$NoNewline -Width $Width -NoFirstLineLeadingSpaces -Log $Log
  1113.  
  1114.                 }
  1115.  
  1116.             } else {
  1117.  
  1118.                 Write-Console -Message $SelectedMessage -BackgroundColor $BackgroundColor -ForegroundColor $SelectColor -NoNewline -Width $Width -Log $Log
  1119.                 Write-Console -Message (($OptionsText -split ($SelectedMessage).Replace('[', '\['))[1]) -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor -NoNewline:$NoNewline -Width $Width -NoFirstLineLeadingSpaces -Log 'Nothing'
  1120.                
  1121.                 if ($Log[0] -ne 'n') {
  1122.                
  1123.                     Write-Console -Message (($OptionsText -split ($SelectedMessage).Replace('[', '\['))[1]).Replace('[', '').Replace(']', '') -NoNewline:$NoNewline -Width $Width -NoFirstLineLeadingSpaces -Log 'Only'
  1124.  
  1125.                 }
  1126.             }
  1127.         }
  1128.     }
  1129.        
  1130.     if ([string]$VariableName -ne '') {
  1131.  
  1132.         if ($DefinedOnly -and $OptionCounter -ne [int]::MaxValue -and $Options[$OptionCounter] -isnot [array]) {
  1133.        
  1134.             if ($ClearUndefined) {
  1135.            
  1136.                 Clear-Variable -Name $VariableName -Scope $Scope 2>$null
  1137.        
  1138.             }
  1139.        
  1140.         } else {
  1141.        
  1142.             if ($Default) {
  1143.            
  1144.                 $Value = [int]::MaxValue
  1145.            
  1146.             } elseif ($MessageAsValue) {
  1147.  
  1148.                 $Value = $Message[$OptionCounter]
  1149.  
  1150.             } elseif ($Options[$OptionCounter] -is [array]) {
  1151.  
  1152.                 $Value = ($Options[$OptionCounter])[1]
  1153.  
  1154.             } else {
  1155.  
  1156.                 $Value = $Options[$OptionCounter]
  1157.  
  1158.             }
  1159.            
  1160.             if ([string]$Value -ne '') {
  1161.            
  1162.                 if ($VariableName -is [array]) {
  1163.                
  1164.                     $VariableName | ForEach-Object {
  1165.                    
  1166.                         Set-Variable -Name $_ -Value $Value -Scope $Scope
  1167.                    
  1168.                     }
  1169.                
  1170.                 } else {
  1171.                
  1172.                     Set-Variable -Name $VariableName -Value $Value -Scope $Scope
  1173.  
  1174.                 }
  1175.             }
  1176.         }
  1177.     }
  1178.    
  1179.     if ($Return) {
  1180.    
  1181.         if ($OptionCounter -eq [int]::MaxValue) {
  1182.        
  1183.             return [int]::MaxValue
  1184.        
  1185.         } else {
  1186.        
  1187.             return $OptionKeys[$OptionCounter]
  1188.    
  1189.         }
  1190.     }
  1191. }
  1192.  
  1193. New-Alias -Name read -Value Read-Console
  1194.  
  1195.  
  1196.  
  1197. <#
  1198. .SYNOPSIS
  1199.  
  1200. Adjusts the console and the console window.
  1201.  
  1202. .Description
  1203.  
  1204. The Set-Console cmdlet adjusts the console and the console window. You can specifie width, buffer width, title, foreground color and background color.
  1205.  
  1206. .PARAMETER WindowSize
  1207. Specifies the console window size. Accepts either an array of width and height or an integer with the width only. Each need to be greater than 0.
  1208.  
  1209. .PARAMETER BufferSize
  1210. Specifies the console window buffer size. Accepts either an array of width and height or an integer with the width only. Each need to be greater than the console window size.
  1211.  
  1212. .PARAMETER WindowTitle
  1213. Specifies the console window title.
  1214.  
  1215. .PARAMETER BackgroundColor
  1216. Specifies the console background color. The acceptable values for this parameter are:
  1217.  
  1218.     - Black
  1219.  
  1220.     - DarkBlue
  1221.  
  1222.     - DarkGreen
  1223.  
  1224.     - DarkCyan
  1225.  
  1226.     - DarkRed
  1227.  
  1228.     - DarkMagenta
  1229.  
  1230.     - DarkYellow
  1231.  
  1232.     - Gray
  1233.  
  1234.     - DarkGray
  1235.  
  1236.     - Blue
  1237.  
  1238.     - Green
  1239.  
  1240.     - Cyan
  1241.  
  1242.     - Red
  1243.  
  1244.     - Magenta
  1245.  
  1246.     - Yellow
  1247.  
  1248.     - White
  1249.    
  1250. Only works properly during script execution.
  1251.  
  1252. .PARAMETER ForegroundColor
  1253. Specifies the console foreground color. The acceptable values for this parameter are:
  1254.  
  1255.     - Black
  1256.  
  1257.     - DarkBlue
  1258.  
  1259.     - DarkGreen
  1260.  
  1261.     - DarkCyan
  1262.  
  1263.     - DarkRed
  1264.  
  1265.     - DarkMagenta
  1266.  
  1267.     - DarkYellow
  1268.  
  1269.     - Gray
  1270.  
  1271.     - DarkGray
  1272.  
  1273.     - Blue
  1274.  
  1275.     - Green
  1276.  
  1277.     - Cyan
  1278.  
  1279.     - Red
  1280.  
  1281.     - Magenta
  1282.  
  1283.     - Yellow
  1284.  
  1285.     - White
  1286.    
  1287. Only works properly during script execution.
  1288.  
  1289. .PARAMETER ClearHost
  1290. Executes the Clear-Host cmdlet. Needed to effectively change background and foreground color of the console.
  1291.  
  1292. .INPUTS
  1293.  
  1294. None
  1295.  
  1296. .OUTPUTS
  1297.  
  1298. None
  1299.  
  1300. .EXAMPLE
  1301.  
  1302. PS> Set-Console -WindowSize 50
  1303.  
  1304. Sets the console window width.
  1305.  
  1306. .EXAMPLE
  1307.  
  1308. PS> Set-Console -BufferSize (120, 9000)
  1309.  
  1310. Sets the console window buffer width and height.
  1311.  
  1312. .EXAMPLE
  1313.  
  1314. PS> Set-Console -WindowTitle 'Some title'
  1315.  
  1316. Sets the console window title.
  1317.  
  1318. .EXAMPLE
  1319.  
  1320. PS> Set-Console -BackgroundColor 'DarkMagenta' -ForegroundColor 'DarkYellow' -ClearHost
  1321.  
  1322. Sets the background and foreground color of the console and calls the Clear-Host cmdlet afterwards.
  1323.  
  1324. .LINK
  1325.  
  1326. https://pastebin.com/9RSusrvC
  1327. Clear-Host
  1328. Get-Host
  1329. #>
  1330.  
  1331. function Set-Console {
  1332.  
  1333.     Param (
  1334.    
  1335.         [Parameter(Mandatory=$false)]
  1336.         [ValidateScript({($_.Count -in 1..2) -and ($_[0] -gt 0 -and ($null -eq $_[1] -or $_[1] -gt 0))})]
  1337.         [int[]] $WindowSize,
  1338.        
  1339.         [Parameter(Mandatory=$false)]
  1340.         [ValidateScript({($_.Count -in 1..2) -and ($_[0] -ge $Host.UI.RawUI.WindowSize.Width -and ($null -eq $_[1] -or $_[1] -ge $Host.UI.RawUI.WindowSize.Height))})]
  1341.         [int[]] $BufferSize,
  1342.        
  1343.         [Parameter(Mandatory=$false)]
  1344.         [Alias('Title')]
  1345.         [string] $WindowTitle,
  1346.        
  1347.         [Parameter(Mandatory=$false)]
  1348.         [Alias('BgC','Background')]
  1349.         [System.ConsoleColor] $BackgroundColor,
  1350.        
  1351.         [Parameter(Mandatory=$false)]
  1352.         [Alias('FC','Fackground')]
  1353.         [System.ConsoleColor] $ForegroundColor,
  1354.        
  1355.         [Parameter(Mandatory=$false)]
  1356.         [Alias('Clear')]
  1357.         [switch] $ClearHost
  1358.        
  1359.     )
  1360.        
  1361.     if ($WindowSize.Count -eq 1) {
  1362.    
  1363.         $Host.UI.RawUI.WindowSize = New-Object System.Management.Automation.Host.Size($WindowSize[0], $Host.UI.RawUI.WindowSize.Height)
  1364.    
  1365.     } elseif ($WindowSize.Count -eq 2) {
  1366.    
  1367.         $Host.UI.RawUI.WindowSize = New-Object System.Management.Automation.Host.Size($WindowSize[0], $WindowSize[1])
  1368.    
  1369.     }
  1370.    
  1371.     if ($BufferSize.Count -eq 1) {
  1372.    
  1373.         $Host.UI.RawUI.BufferSize = New-Object System.Management.Automation.Host.Size($BufferSize[0], $Host.UI.RawUI.BufferSize.Height)
  1374.    
  1375.     } elseif ($BufferSize.Count -eq 2) {
  1376.    
  1377.         $Host.UI.RawUI.BufferSize = New-Object System.Management.Automation.Host.Size($BufferSize[0], $BufferSize[1])
  1378.    
  1379.     }
  1380.    
  1381.     if ([string]$WindowTitle -ne '') {
  1382.    
  1383.         $Host.UI.RawUI.WindowTitle = $WindowTitle
  1384.    
  1385.     }
  1386.    
  1387.     if ([string]$ForegroundColor -ne '') {
  1388.    
  1389.         $Host.UI.RawUI.ForegroundColor = $ForegroundColor
  1390.    
  1391.     }
  1392.    
  1393.     if ([string]$BackgroundColor -ne '') {
  1394.    
  1395.         $Host.UI.RawUI.BackgroundColor = $BackgroundColor
  1396.        
  1397.     }
  1398.    
  1399.     if ($ClearHost) {
  1400.    
  1401.         Clear-Host
  1402.    
  1403.     }
  1404. }
  1405.  
  1406. New-Alias -Name adjust -Value Set-Console
  1407.  
  1408.  
  1409.  
  1410. <#
  1411. .SYNOPSIS
  1412.  
  1413. Writes customized output to the console.
  1414.  
  1415. .Description
  1416.  
  1417. The Write-Console cmdlet customizes output similiar to the Write-Host cmdlet, but it inserts new line characters in between words if the string to be displayed exceeds the buffer width of the console window.
  1418. It also comes with a typewriter effect and delays.
  1419.  
  1420. .PARAMETER Message
  1421. Specifies the message to display in the console.
  1422.  
  1423. .PARAMETER BackgroundColor
  1424. Specifies the background color. The acceptable values for this parameter are:
  1425.  
  1426.     - Black
  1427.  
  1428.     - DarkBlue
  1429.  
  1430.     - DarkGreen
  1431.  
  1432.     - DarkCyan
  1433.  
  1434.     - DarkRed
  1435.  
  1436.     - DarkMagenta
  1437.  
  1438.     - DarkYellow
  1439.  
  1440.     - Gray
  1441.  
  1442.     - DarkGray
  1443.  
  1444.     - Blue
  1445.  
  1446.     - Green
  1447.  
  1448.     - Cyan
  1449.  
  1450.     - Red
  1451.  
  1452.     - Magenta
  1453.  
  1454.     - Yellow
  1455.  
  1456.     - White
  1457.  
  1458. The default value is $Host.UI.RawUI.BackgroundColor.
  1459.  
  1460. .PARAMETER ForegroundColor
  1461. Specifies the foreground color. The acceptable values for this parameter are:
  1462.  
  1463.     - Black
  1464.  
  1465.     - DarkBlue
  1466.  
  1467.     - DarkGreen
  1468.  
  1469.     - DarkCyan
  1470.  
  1471.     - DarkRed
  1472.  
  1473.     - DarkMagenta
  1474.  
  1475.     - DarkYellow
  1476.  
  1477.     - Gray
  1478.  
  1479.     - DarkGray
  1480.  
  1481.     - Blue
  1482.  
  1483.     - Green
  1484.  
  1485.     - Cyan
  1486.  
  1487.     - Red
  1488.  
  1489.     - Magenta
  1490.  
  1491.     - Yellow
  1492.  
  1493.     - White
  1494.  
  1495. The default value is $Host.UI.RawUI.ForegroundColor.
  1496.  
  1497. .PARAMETER NoNewline
  1498. Specifies that the content displayed in the console does not end with a newline character.
  1499.  
  1500. .PARAMETER Seperator
  1501. Inserts either a small, normal or big horizontal seperator.
  1502.  
  1503. .PARAMETER Width
  1504. Specifies the window buffer width. The default value is set by the variable $DefaultWidth.
  1505.  
  1506. .PARAMETER LeadingSpaces
  1507. Specifies the amount of leading spaces. The default value is set by the variable $DefaultLeadingSpaces.
  1508.  
  1509. .PARAMETER NoFirstLineLeadingSpaces
  1510. Specifies that no leading spaces will be inserted at the beginning of the first line.
  1511.  
  1512. .PARAMETER Typewriter
  1513. Specifies that the text will be displayed with a typewriter animation.
  1514. Delays are generated randomly. Each alphanumeric character and dot has a delay of 25ms - 75ms, all other characters have a delay of 50ms - 100ms. Use '`p(x)' or "``p(x)" to insert an additional delay of x ms.
  1515. The default value is set by the variable $DefaultTypewriter.
  1516.  
  1517. .PARAMETER Log
  1518. Specifies log behaviour. The default value is ''.
  1519.  
  1520. .INPUTS
  1521.  
  1522. None
  1523.  
  1524. .OUTPUTS
  1525.  
  1526. Write-Console uses the Write-Host cmdlet to send the message to the host. It does not return any message. However, the host might display the message that Write-Host sends to it.
  1527.  
  1528. .EXAMPLE
  1529.  
  1530. PS> Write-Console -Message 'Some string' -NoNewline -LeadingSpaces 4 -Log 'Nothing'
  1531.     Some string
  1532.  
  1533. Displays the message with 4 spaces (or 1 tab) inserted in front of the string and every following line if the string exceeds the maximum width. At the end of the string there is no newline character being added, so the next will be added at the end of the string on the same line.
  1534.  
  1535. .EXAMPLE
  1536.  
  1537. PS> Write-Console -Message 'A string which is quite long and therefore has new line characters inserted so the specified width is not exceeded' -Width 40 -NoFirstLineLeadingSpaces
  1538. A string which is quite long and
  1539.  therefore has new line characters
  1540.  inserted so the specified width is not
  1541.  exceeded
  1542.  
  1543. Displays the message and splits it so no line exceeds the width of 40 characters.
  1544. There are no leading spaces at the start of the string.
  1545.  
  1546. .EXAMPLE
  1547.  
  1548. PS> Write-Console -Seperator 'Big'
  1549. ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
  1550.  
  1551. .EXAMPLE
  1552.  
  1553. PS> Write-Console -Message 'Some string' -BackgroundColor Black -ForegroundColor Cyan -Typewriter
  1554. Some string
  1555.  
  1556. Displays the message with a typewriter effect. The background color is black and the foreground color is cyan.
  1557.  
  1558. .LINK
  1559.  
  1560. https://pastebin.com/9RSusrvC
  1561. Write-Host
  1562. #>
  1563.  
  1564. function Write-Console {
  1565.    
  1566.     Param (
  1567.  
  1568.         [Parameter(Mandatory=$true,
  1569.         Position=0,
  1570.         ParameterSetName='Write')]
  1571.         [Alias('Msg','Object')]
  1572.         [AllowNull()]
  1573.         [AllowEmptyString()]
  1574.         [string[]] $Message,
  1575.        
  1576.         [Parameter(Mandatory=$false)]
  1577.         [Alias('BgC','Background')]
  1578.         [System.ConsoleColor] $BackgroundColor = $Host.UI.RawUI.BackgroundColor,
  1579.        
  1580.         [Parameter(Mandatory=$false)]
  1581.         [Alias('FgC','Foreground')]
  1582.         [System.ConsoleColor] $ForegroundColor = $Host.UI.RawUI.ForegroundColor,
  1583.        
  1584.         [Parameter(Mandatory=$false)]
  1585.         [switch] $NoNewline,
  1586.        
  1587.         [Parameter(Mandatory=$true,
  1588.         ParameterSetName='WriteSeperator')]
  1589.         [ValidateSet('Small', 's', 'Normal', 'n', 'Big', 'b')]
  1590.         [string] $Seperator = '',
  1591.        
  1592.         [Parameter(Mandatory=$false)]
  1593.         [ValidateScript({[int]$_ -gt ($Message -split " |`n" | Sort-Object -Property Length -Descending | Select-Object -First 1 -ExpandProperty Length) + 4})]
  1594.         [int] $Width = $DefaultWidth,
  1595.        
  1596.         [Parameter(Mandatory=$false,
  1597.         ParameterSetName='Write')]
  1598.         [Alias('LS')]
  1599.         [ValidateScript({if ([int]$Width -eq 0) {[int]$_ -ge 0 -and [int]$_ -lt $DefaultWidth} else {[int]$_ -ge 0 -and [int]$_ -lt $Width}})]
  1600.         [int] $LeadingSpaces = $DefaultLeadingSpaces,
  1601.        
  1602.         [Parameter(Mandatory=$false,
  1603.         ParameterSetName='Write')]
  1604.         [Alias('NoLS')]
  1605.         [switch] $NoFirstLineLeadingSpaces,
  1606.        
  1607.         [Parameter(Mandatory=$false,
  1608.         ParameterSetName='Write')]
  1609.         [switch] $Typewriter = $DefaultTypewriter,
  1610.        
  1611.         [Parameter(Mandatory=$false)]
  1612.         [ValidateSet('Only', 'o', 'Nothing', 'n', '')]
  1613.         [string] $Log = ''
  1614.  
  1615.     )
  1616.    
  1617.     if ([string]$Seperator -ne '') {
  1618.    
  1619.         if ($Seperator[0] -eq 's') {
  1620.        
  1621.             $Output = ('─' * $Width)
  1622.        
  1623.         } elseif ($Seperator[0] -eq 'n') {
  1624.        
  1625.             $Output = ('═' * $Width)
  1626.        
  1627.         } else {
  1628.        
  1629.             $Output = ('▄' * $Width + "`n")
  1630.        
  1631.         }
  1632.    
  1633.     } else {
  1634.        
  1635.         $Output = (' ' * $LeadingSpaces)
  1636.         $CursorPosX = $Host.UI.RawUI.CursorPosition.X
  1637.        
  1638.         $Message -split "`n" | ForEach-Object {
  1639.        
  1640.             $CurObj = $_
  1641.            
  1642.             if ($Counter1++ -gt 0) {
  1643.            
  1644.                 $Output += ("`n" + ' ' * $LeadingSpaces)
  1645.                 $CursorPosX = $LeadingSpaces
  1646.            
  1647.             }
  1648.            
  1649.             while (($CurObj -replace '`p\([0-9]+?\)').Length -ge $Width - ($Output.Length - [Math]::Abs($Output.LastIndexOf("`n"))) - $CursorPosX) {
  1650.            
  1651.                 if ($Counter2++ -gt 0) {
  1652.        
  1653.                     $Output += ("`n" + ' ' * $LeadingSpaces)
  1654.                     $CursorPosX = $LeadingSpaces
  1655.                
  1656.                 }
  1657.                
  1658.                 $pLength = -1
  1659.                
  1660.                 Select-String -Pattern '`p\([0-9]+?\)' -AllMatches -InputObject $CurObj | Select-Object -ExpandProperty Matches | ForEach-Object {
  1661.                
  1662.                     if ($CurObj.Length -ge ($Width + $pLength + $_.Length - ($Output.Length - [Math]::Abs($Output.LastIndexOf("`n"))) - $CursorPosX) -and $_.Index -le ($CurObj.Substring(0, $Width + $pLength + $_.Length - ($Output.Length - [Math]::Abs($Output.LastIndexOf("`n"))) - $CursorPosX).LastIndexOf(' '))) {
  1663.                    
  1664.                         $pLength += $_.Length
  1665.                    
  1666.                     }
  1667.                 }
  1668.                
  1669.                 if ($CurObj.Length -ge ($End = $Width + $pLength - ($Output.Length - [Math]::Abs($Output.LastIndexOf("`n"))) - $CursorPosX)) {
  1670.                
  1671.                     if ($CurObj.Contains(' ')) {
  1672.                    
  1673.                         if ($CurObj.Substring(0, $End).Contains(' ')) {
  1674.                        
  1675.                             $Output += $CurObj.Substring(0, ($SpaceIndex = $CurObj.Substring(0, $End).LastIndexOf(' ')))
  1676.                             $CurObj = $CurObj.Substring($SpaceIndex + 1)
  1677.                        
  1678.                         } else {
  1679.                        
  1680.                             $Output += $CurObj.Substring(0, ($SpaceIndex = $CurObj.LastIndexOf(' ')))
  1681.                             $CurObj = $CurObj.Substring($SpaceIndex + 1)
  1682.                            
  1683.                         }
  1684.                    
  1685.                     } else {
  1686.                    
  1687.                         $Output += $CurObj
  1688.                         $CurObj = ''
  1689.                    
  1690.                     }
  1691.                 }
  1692.             }
  1693.            
  1694.             if ($Counter2 -eq 1) {
  1695.            
  1696.                 $Output += ("`n" + ' ' * $LeadingSpaces)
  1697.            
  1698.             }
  1699.            
  1700.             $Output += $CurObj
  1701.            
  1702.         }
  1703.        
  1704.         if ($NoFirstLineLeadingSpaces) {
  1705.        
  1706.             $Output = $Output.Substring($LeadingSpaces)
  1707.        
  1708.         }
  1709.     }
  1710.    
  1711.     if ($Log[0] -ne 'n' -and [string]$LogFilePath -ne '') {
  1712.    
  1713.         Add-Content -Value $Output -LiteralPath $LogFilePath -NoNewline:$NoNewline -Encoding UTF8
  1714.    
  1715.     }
  1716.    
  1717.     if ($Log[0] -ne 'o') {
  1718.    
  1719.         $Output -split '(`p\([0-9]+?\))' | ForEach-Object {
  1720.        
  1721.             if ($_ -match '`p\([0-9]+?\)') {
  1722.            
  1723.                 Start-Sleep -Milliseconds ([int]($Matches.0).Trim('`p()'))
  1724.            
  1725.             } elseif ($Typewriter) {
  1726.            
  1727.                 $_ -split '.*?' | ForEach-Object {
  1728.                
  1729.                     Write-Host -Object $_ -ForegroundColor $ForegroundColor -BackgroundColor $BackgroundColor -NoNewline
  1730.                    
  1731.                     if ($_ -notmatch '[A-z0-9]|') {
  1732.                    
  1733.                         Start-Sleep -Milliseconds (Get-Random -Minimum 75 -Maximum 150)
  1734.                    
  1735.                     } else {
  1736.                    
  1737.                         Start-Sleep -Milliseconds (Get-Random -Minimum 25 -Maximum 75)
  1738.                
  1739.                     }
  1740.                 }
  1741.                
  1742.             } else {
  1743.            
  1744.                 Write-Host -Object $_ -ForegroundColor $ForegroundColor -BackgroundColor $BackgroundColor -NoNewline
  1745.            
  1746.             }
  1747.         }
  1748.            
  1749.         if (!$NoNewline) {
  1750.        
  1751.             Write-Host -Object ''
  1752.        
  1753.         }
  1754.     }
  1755. }
  1756.  
  1757. New-Alias -Name wc -Value Write-Console
  1758. Export-ModuleMember -Alias * -Function *
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement