Thursday, April 18, 2024
HomePowershellAn Iron Scripter Heat-Up Resolution • The Lonely Administrator

An Iron Scripter Heat-Up Resolution • The Lonely Administrator


We simply wrapped up the 2022 version of the PowerShell+DevOps International Summit. It was terrific to be with passionate PowerShell professionals once more. The fruits of the occasion is the Iron Scripter Problem. You may study extra about this yr’s occasion and winner right here. However there’s extra to the Iron Scripter than this occasion. All year long, yow will discover scripting challenges to check your PowerShell talent at https://ironscripter.us. You might be inspired to share hyperlinks to your options within the feedback. Right this moment, I’ve my options for a latest problem.

Handle and Report Energetic Listing, Change and Microsoft 365 with
ManageEngine ADManager Plus – Obtain Free Trial

The nice and cozy-up problem was all about manipulating strings. That alone might not sound like a lot. However the means of discovering find out how to do it and wrapping it up in a PowerShell operate is the place the true worth lies.

Newbie Degree: Write PowerShell code to take a string like ‘PowerShell’ and show it in reverse.

Intermediate Degree: Take a sentence like, “That is how one can enhance your PowerShell abilities.” and write PowerShell code to show all the sentence in reverse with every phrase additionally reversed. It’s best to have the ability to encode and decode textual content. Ideally, your capabilities ought to take pipeline enter. For bonus factors, toggle higher and decrease case when reversing the phrase.

Reversing Textual content

PowerShell treats each string of textual content as an array.

PS C:> $w = "PowerShell"
PS C:> $w[0]
P

Utilizing the vary operator, I can get parts in reverse.

PS C:> $w[-1..-($w.length)]
l
l
e
h
S
r
e
w
o
P

Use the Be a part of operator to place the characters again collectively once more.

PS C:> $w[-1..-($w.length)] -join ''
llehSrewoP

With this core idea validated, it’s easy sufficient to wrap it in a operate.

Operate Invoke-ReverseWord {
    [cmdletbinding()]
    [OutputType("string")]
    Param(
        [Parameter(
            Position = 0,
            Mandatory,
            ValueFromPipeline,
            HelpMessage = "Enter a word."
        )]
        [ValidateNotNullOrEmpty()]
        [string]$Phrase
    )

    Start {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Beginning $($myinvocation.mycommand)"
    } #start
    Course of {
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Processing $Phrase"
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Phrase size is $($Phrase.size)"
        #get the characters in reverse and be part of right into a string
        ($Phrase[-1.. -($Word.length)]) -join ''

    } #course of
    Finish {
        Write-Verbose "[$((Get-Date).TimeofDay) END    ] Ending $($myinvocation.mycommand)"
    } #finish
}

Reversing a Sentence

Reversing phrases in a sentence follows the identical precept. I can cut up the sentence into an array of phrases after which entry the weather in reverse.

PS C:> $t = "That is how one can enhance your PowerShell abilities"
PS C:> $phrases = $t.cut up()
PS C:> $phrases[-1..-($words.count)]
abilities
PowerShell
your
enhance
can
you
how
is
This

Once more, I can be part of the phrases with an area. If I needed to, I may reverse every phrase as nicely. That’s what this operate does.

Operate Invoke-ReverseText {
    [CmdletBinding()]
    [OutputType("string")]
    Param(
        [Parameter(
            Position = 0,
            Mandatory,
            ValueFromPipeline,
            HelpMessage = "Enter a phrase."
        )]
        [ValidateNotNullOrEmpty()]
        [ValidatePattern("s")]
        [string]$Textual content
    )
    Start {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Beginning $($myinvocation.mycommand)"
    } #start
    Course of  Invoke-ReverseWord
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Reversed $($phrases.depend) phrases"
        ($phrases[-1.. - $($words.count)]) -join " "
     #course of
    Finish {
        Write-Verbose "[$((Get-Date).TimeofDay) END    ] Ending $($myinvocation.mycommand)"
    } #finish
}
PS C:> Invoke-ReverseText "That is how one can enhance your PowerShell abilities"
slliks llehSrewoP ruoy evorpmi nac uoy woh si sihT
PS C:> Invoke-ReverseText "That is how one can enhance your PowerShell abilities" | invoke-reversetext
That is how one can enhance your PowerShell abilities
PS C:>

Toggle Case

Determining find out how to toggle case is a bit trickier. Every letter in a phrase is technically a [Char] sort object.

PS C:> $t = "PowerShell"
PS C:> $t[0]
P
PS C:> $t[0].gettype()

IsPublic IsSerial Identify                                     BaseType
-------- -------- ----                                     --------
True     True     Char                                     System.ValueType

[Char] objects have a numeric worth.

PS C:> $t[0] -as [int]
80

On my en-US system, upper-case alphabet characters fall throughout the vary of 65-90. Decrease-case letters are 97-112.

PS C:> [char]80     
P
PS C:> 100 -as [char]
d

To toggle case, I must get the numeric worth of every character after which invoke the toLower() or toUpper() methodology as required.

Operate Invoke-ToggleCase {
    [cmdletbinding()]
    [OutputType("String")]
    Param(
        [Parameter(
            Position = 0,
            Mandatory,
            ValueFromPipeline,
            HelpMessage = "Enter a word."
        )]
        [ValidateNotNullOrEmpty()]
        [string]$Phrase
    )

    Start {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Beginning $($myinvocation.mycommand)"
    } #start
    Course of {
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Processing $Phrase"
        $Toggled = $Phrase.ToCharArray() | ForEach-Object {
            $i = $_ -as [int]
            if ($i -ge 65 -AND $i -le 90) {
                #toggle decrease
                $_.ToString().ToLower()
            }
            elseif ($i -ge 97 -AND $i -le 122) {
                #toggle higher
                $_.ToString().ToUpper()
            }
            else {
                $_.ToString()
            }
        } #foreach-object

        #write the brand new phrase to the pipeline
        $toggled -join ''

    } #course of
    Finish {
        Write-Verbose "[$((Get-Date).TimeofDay) END    ] Ending $($myinvocation.mycommand)"
    } #finish

}
PS C:> invoke-togglecase $t
pOWERsHELL

Placing It All Collectively

Right here’s a operate that does all of it.

Operate Invoke-ReverseTextToggle {
    [CmdletBinding()]
    [OutputType("string")]
    Param(
        [Parameter(
            Position = 0,
            Mandatory,
            ValueFromPipeline,
            HelpMessage = "Enter a phrase."
        )]
        [ValidateNotNullOrEmpty()]
        [ValidatePattern("s")]
        [string]$Textual content
    )
    Start {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Beginning $($myinvocation.mycommand)"
    } #start
    Course of  Invoke-ToggleCase  #course of
    Finish {
        Write-Verbose "[$((Get-Date).TimeofDay) END    ] Ending $($myinvocation.mycommand)"
    } #finish
}
PS C:> Invoke-ReverseTextToggle "That is how YOU can enhance your PowerShell abilities"
SLLIKS LLEHsREWOp RUOY EVORPMI NAC uoy WOH SI SIHt
PS C:>
PS C:> Invoke-ReverseTextToggle "That is how YOU can enhance your PowerShell abilities" | Invoke-ReverseTextToggle
That is how YOU can enhance your PowerShell abilities

After placing that collectively, I spotted somebody won’t need the entire transformations. Possibly they solely need to toggle case and reverse phrases. Right here’s a operate that provides flexibility.

Operate Convert-Textual content {
    <#
    This operate depends on a few of the earlier capabilities or the capabilities could possibly be nested
    contained in the Start block

    Order of operation:
      toggle case
      reverse phrase
      reverse textual content
    #>
    [cmdletbinding()]
    Param(
        [Parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [string]$Textual content,
        [Parameter(HelpMessage = "Reverse each word of text")]
        [switch]$ReverseWord,
        [Parameter(HelpMessage = "Toggle the case of the text")]
        [switch]$ToggleCase,
        [Parameter(HelpMessage = "Reverse the entire string of text")]
        [switch]$ReverseText
    )
    Start {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Beginning $($myinvocation.mycommand)"
    } #start

    Course of {
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Changing $Textual content"
        $phrases = $textual content.Cut up()
        if ($ToggleCase)  Invoke-ToggleCase
        
        If ($reverseWord)  Invoke-ReverseWord
        
        if ($ReverseText) {
            Write-Verbose "reversing textual content"
            $phrases = ($phrases[-1.. - $($words.count)])
        }
        #write the transformed textual content to the pipeline
        $phrases -join " "

    } #course of

    Finish {
        Write-Verbose "[$((Get-Date).TimeofDay) END    ] Ending $($myinvocation.mycommand)"
    } #finish

} #shut Convert-Textual content

As written, this operate depends on a few of the earlier capabilities. However now, the person has choices.

PS C:> convert-text "I AM an Iron Scripter!" -ToggleCase
i'm AN iRON sCRIPTER!
PS C:>
PS C:> convert-text "I AM an Iron Scripter!" -ReverseWord
I MA na norI !retpircS
PS C:>
PS C:> convert-text "I AM an Iron Scripter!" -ReverseWord -ToggleCase
i ma NA NORi !RETPIRCs
PS C:>
PS C:> convert-text "I AM an Iron Scripter!" -Reversetext -ToggleCase -ReverseWord
!RETPIRCs NORi NA ma i
PS C:>
PS C:> convert-text "I AM an Iron Scripter!" -Reversetext -ToggleCase -ReverseWord | convert-text -ReverseWord -ToggleCase -ReverseText   
I AM an Iron Scripter!

Problem Your self

You probably have any questions on my code samples, please be at liberty to depart a remark. I additionally need to emphasize that my options are not the one solution to obtain these outcomes. There’s worth in evaluating your work with others. I strongly encourage you to observe for future Iron Scripter challenges and deal with as a lot as attainable. Nonetheless, you don’t have to attend. There are many present challenges on the positioning for all PowerShell scripting ranges. Feedback could also be closed, so you may’t share your answer, however that shouldn’t stop you from ramping your abilities.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments