#requires -version 2.0 # ----------------------------------------------------------------------------- # Script: stringfun.ps1 # Author: Jeffery Hicks # http://jdhitsolutions.com/blog # Date: 9/16/2010 # Keywords: # Comments: # # Learn more with a copy of Windows PowerShell 2.0: TFM (SAPIEN Press 2010) # ----------------------------------------------------------------------------- Function Out-Reverse { Param( [Parameter(Position=0,Mandatory=$True,HelpMessage="Enter a line of text", ValueFromPipeline=$True)] [ValidateNotNullorEmpty()] [string[]]$Text ) Process { ForEach ($str in $Text) { Write-Verbose "Reversing: $str" $str | foreach { #define an empty variable for the reversed result [string]$reverse="" for ($i=($_.length-1);$i -ge 0; $i--) { #append to $reverse $reverse+=$_[$i] } #write the result Write-Host "Reversed" -ForegroundColor Yellow $reverse } }# Foreach } #process } #end function Function Out-Random { Param( [Parameter(Position=0,Mandatory=$True,HelpMessage="Enter a line of text", ValueFromPipeline=$True)] [ValidateNotNullorEmpty()] [string[]]$Text ) Process { ForEach ($str in $Text) { Write-Verbose "Randomizing: $str" #initialize an empty array $a=@() Write-Verbose "Generating random number array" do { #get a random number between 0 and length of string $x=get-random -Minimum 0 -Maximum $str.length #add the number to the array if it doesn't already exist if (-not ($a -contains $x)) { $a+=$x } #repeat until every number has been added to the array } Until ($a.count -eq $str.length) #define a varialble for the randomized output [string]$randout="" Write-Verbose "Constructing random output" #get the corresponding random element and construct the random output $a | foreach { $randout+=$str[$_] } #write the result Write-Host "Randomized" -ForegroundColor Yellow $randout } #foreach } #Process } #end function #Examples "Every good boy deserves fudge." | out-reverse "Every good boy deserves fudge." | out-random write-host "Random and reversed" -ForegroundColor Green "Every good boy deserves fudge." | out-random | out-reverse write-host "Reversed and random" -ForegroundColor Green "Every good boy deserves fudge." | out-reverse | out-random $a="Every good boy deserves fudge." | out-reverse write-host $a -ForegroundColor Green #now undo it write-host "Undone" -ForegroundColor Green $a | out-reverse