Saturday, 30 May 2015

Prompt Validator PowerShell Function

Another potentially useful function if you have lots of prompts in your PowerShell script/program.

Usage Examples:

$Answer = PromptValidator
$Answer = PromptValidator -YesOrNo
$Answer = PromptValidator "Bananas"
$Answer = PromptValidator "Bananas","Apples","Pears" -CaseSensitive
$Answer = PromptValidator "NotDefault1","NotDefault2" -AllowCR

In the last example, carriage return would give you the default option say.

The Code:

FUNCTION PromptValidator{
   [System.Array]$Answers = $In
   WHILE ($true){
      $ReadIn = Read-Host
      IF($YesOrNo){ IF( ($ReadIn -eq "YES") -or ($ReadIn -eq "Y") ){ RETURN $TRUE  } }
      IF($YesOrNo){ IF( ($ReadIn -eq "NO")  -or ($ReadIn -eq "N") ){ RETURN $FALSE } }
      IF($Answers -and  $CaseSensitive){ FOREACH ($a in $Answers){ IF($ReadIn -ceq $a){ RETURN $ReadIn } } }
      IF($Answers -and !$CaseSensitive){ FOREACH ($a in $Answers){ IF($ReadIn -eq  $a){ RETURN $ReadIn } } }
      IF(!$YesOrNo -and !$Answers -and ($ReadIn.length -gt 0) ){ RETURN $ReadIn }
      IF(!$YesOrNo -and $AllowCR  -and ($ReadIn.length -eq 0) ){ RETURN $NULL }

Monday, 25 May 2015

Simple Multi-Color Foreground Background Powershell Display Function

Apologies the blog’s been very quiet recently, been working on some major projects, and a couple of fairly major PowerShell tools. Still, I’ve found time for a favourite little function!

The one-line of code:

FUNCTION WrB { $i = 0; While ($i -lt $Args.Count){ Write-Host $Args[$i] -ForegroundColor $Args[$i+1] -BackgroundColor $Args[$i+2] -NoNewLine; $i+=3 } }

And an example of its use:

WrB "G" Blue White "o" Red White "o" Yellow White "g" Blue White "l" Green White "e" Red White

Image: Output - The Famous Google Sign in PowerShell!