当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] Iron Scripter 热身解决方案

作者:精品下载站 日期:2024-12-14 08:07:02 浏览:13 分类:玩电脑

Iron Scripter 热身解决方案


我们刚刚结束了 2022 年 PowerShell+DevOps 全球峰会。再次与充满热情的 PowerShell 专业人士在一起真是太棒了。该活动的高潮是 Iron Scripter 挑战赛。您可以在此处了解有关今年活动和获奖者的更多信息。但对于钢铁脚本家来说,还有比这个事件更多的事情。全年,您都可以在 https://ironscripter.us 找到脚本编写挑战来测试您的 PowerShell 技能。我们鼓励您在评论中分享您的解决方案的链接。今天,我针对最近的挑战提出了解决方案。

热身挑战都是关于操纵弦乐的。仅此一点听起来可能并不多。但发现如何做到这一点并将其包装在 PowerShell 函数中的过程才是真正的价值所在。

初级水平:编写 PowerShell 代码以获取类似“PowerShell”的字符串并将其反向显示。

中级水平:采用类似这样的句子:“这就是您如何可以提高您的 PowerShell 技能。”并编写 PowerShell 代码以反转显示整个句子,并且每个单词也反转。您应该能够对文本进行编码和解码。理想情况下,您的函数应该采用管道输入。 为了获得奖励积分,请在反转单词时切换大小写。

反转文本

PowerShell 将每个文本字符串视为一个数组。

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

使用范围运算符,我可以反向获取元素。

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

使用连接运算符将字符重新组合在一起。

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

通过验证这个核心概念,将其包装在函数中就足够简单了。

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

    Begin {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Starting $($myinvocation.mycommand)"
    } #begin
    Process {
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Processing $Word"
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Word length is $($Word.length)"
        #get the characters in reverse and join into a string
        ($Word[-1.. -($Word.length)]) -join ''

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

反转句子

句子中的单词反转遵循相同的原则。我可以将句子拆分为单词数组,然后反向访问元素。

PS C:\> $t = "This is how you can improve your PowerShell skills"
PS C:\> $words = $t.split()
PS C:\> $words[-1..-($words.count)]
skills
PowerShell
your
improve
can
you
how
is
This

同样,我可以用空格将单词连接起来。如果我愿意,我也可以颠倒每个单词。这就是这个函数的作用。

Function Invoke-ReverseText {
    [CmdletBinding()]
    [OutputType("string")]
    Param(
        [Parameter(
            Position = 0,
            Mandatory,
            ValueFromPipeline,
            HelpMessage = "Enter a phrase."
        )]
        [ValidateNotNullOrEmpty()]
        [ValidatePattern("\s")]
        [string]$Text
    )
    Begin {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Starting $($myinvocation.mycommand)"
    } #begin
    Process {
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Processing $Text"
        #split the phrase on white spaces and reverse each word
        $words = $Text.split() | Invoke-ReverseWord
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Reversed $($words.count) words"
        ($words[-1.. - $($words.count)]) -join " "
    } #process
    End {
        Write-Verbose "[$((Get-Date).TimeofDay) END    ] Ending $($myinvocation.mycommand)"
    } #end
}
PS C:\> Invoke-ReverseText "This is how you can improve your PowerShell skills"
slliks llehSrewoP ruoy evorpmi nac uoy woh si sihT
PS C:\> Invoke-ReverseText "This is how you can improve your PowerShell skills" | invoke-reversetext
This is how you can improve your PowerShell skills
PS C:\>

切换大小写

弄清楚如何切换大小写有点棘手。从技术上讲,单词中的每个字母都是一个 [Char] 类型对象。

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

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

[Char] 对象具有数值。

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

在我的 en-US 系统上,大写字母字符的范围为 65-90。小写字母为 97-112。

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

要切换大小写,我需要获取每个字符的数值,然后根据需要调用 toLower() 或 toUpper() 方法。

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

    Begin {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Starting $($myinvocation.mycommand)"
    } #begin
    Process {
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Processing $Word"
        $Toggled = $Word.ToCharArray() | ForEach-Object {
            $i = $_ -as [int]
            if ($i -ge 65 -AND $i -le 90) {
                #toggle lower
                $_.ToString().ToLower()
            }
            elseif ($i -ge 97 -AND $i -le 122) {
                #toggle upper
                $_.ToString().ToUpper()
            }
            else {
                $_.ToString()
            }
        } #foreach-object

        #write the new word to the pipeline
        $toggled -join ''

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

}
PS C:\> invoke-togglecase $t
pOWERsHELL

把它们放在一起

这是一个可以完成这一切的函数。

Function Invoke-ReverseTextToggle {
    [CmdletBinding()]
    [OutputType("string")]
    Param(
        [Parameter(
            Position = 0,
            Mandatory,
            ValueFromPipeline,
            HelpMessage = "Enter a phrase."
        )]
        [ValidateNotNullOrEmpty()]
        [ValidatePattern("\s")]
        [string]$Text
    )
    Begin {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Starting $($myinvocation.mycommand)"
    } #begin
    Process {
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Processing $Text"
        #split the phrase on white spaces and reverse each word
        $words = $Text.split() | Invoke-ToggleCase | Invoke-ReverseWord
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Reversed $($words.count) words"
        ($words[-1.. - $($words.count)]) -join " "
    } #process
    End {
        Write-Verbose "[$((Get-Date).TimeofDay) END    ] Ending $($myinvocation.mycommand)"
    } #end
}
PS C:\> Invoke-ReverseTextToggle "This is how YOU can improve your PowerShell skills"
SLLIKS LLEHsREWOp RUOY EVORPMI NAC uoy WOH SI SIHt
PS C:\>
PS C:\> Invoke-ReverseTextToggle "This is how YOU can improve your PowerShell skills" | Invoke-ReverseTextToggle
This is how YOU can improve your PowerShell skills

将它们放在一起之后,我意识到有人可能不想要所有的转换。也许他们只想切换大小写和反转单词。这是一个提供灵活性的函数。

Function Convert-Text {
    <#
    This function relies on some of the previous functions or the functions could be nested
    inside the Begin block

    Order of operation:
      toggle case
      reverse word
      reverse text
    #>
    [cmdletbinding()]
    Param(
        [Parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [string]$Text,
        [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
    )
    Begin {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Starting $($myinvocation.mycommand)"
    } #begin

    Process {
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Converting $Text"
        $words = $text.Split()
        if ($ToggleCase) {
            Write-Verbose "toggling case"
            $words = $words | Invoke-ToggleCase
        }
        If ($reverseWord) {
            Write-Verbose "reversing words"
            $words = $words | Invoke-ReverseWord
        }
        if ($ReverseText) {
            Write-Verbose "reversing text"
            $words = ($words[-1.. - $($words.count)])
        }
        #write the converted text to the pipeline
        $words -join " "

    } #process

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

} #close Convert-Text

正如所写,这个函数依赖于一些早期的函数。但现在,用户有选择。

PS C:\> convert-text "I AM an Iron Scripter!" -ToggleCase
i am 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!

挑战自己

如果您对我的代码示例有任何疑问,请随时发表评论。我还想强调,我的解决方案并不是实现这些结果的唯一方法。将您的工作与其他人进行比较是有价值的。我强烈鼓励您关注 Iron Scripter 未来的挑战并尽可能多地应对。但是,您不必等待。该网站上存在针对所有 PowerShell 脚本编写级别的大量挑战。评论可能会被关闭,因此您无法分享您的解决方案,但这不应妨碍您提高技能。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯