清理 powershell 中是/否提示的方法

清理 powershell 中是/否提示的方法

因此,他们给了我一份他们想要使用的“自动化”脚本。但我从未在 Powershell 中写过任何东西,因此我自然而然地从头开始重写了整个脚本,因为它是战利品(并不是说我的脚本好很多),但经过 5 天的 Powershell 体验,我认为我已经取得了不错的进步。但是,我的是/否提示变得相当混乱,我希望真正了解他们在这里做什么的人能给我一些提示。所以这是我的代码。

这些是提示声明...

    $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&yes"
    $no = New-Object System.Management.Automation.Host.ChoiceDescription "&no"
    $help = New-Object System.Management.Automation.Host.ChoiceDescription "&help"
    $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no, $help)


These are part of the checks for the Datacenter portion. (The whole script block is Datacenters, Clusters, Hosts utilizing VMware PowerCLI.)

    While ($ChoiceTask -eq "Check Datacenters"){
        Clear-Host
        Write-Output "Would you like to create any Datacenters?"
            $result = $host.ui.PromptForChoice($title, $message, $options, 0)
                switch($result){
                    0{$ChoiceTask = "Datacenters"
                    $MadeDatacenters = $true}
                    1{$ChoiceTask = "Check Clusters"
                    $MadeDatacenters = $false}
                    2{
                Write-Output "A virtual datacenter is a container for all the inventory objects required to
    complete a fully functional environment for operating virtual machines.
    Recommended procedure is creating three datacenters. The UCS Datacenter, the vSAN
    Datacenter, and the Witness Datacenter. However, you may change this to fit your needs."
                Read-Host -Prompt "(Press 'Enter' to continue)"
                    }
                }
    }

    #Creates appropriate amount of Datacenters for User

    While ($ChoiceTask -eq "Datacenters"){
        Clear-Host
        $DataCenterAmount = ([String] $DataCenterAmount = (Read-Host "How many datacenters would you like to create?"))
        Clear-Host
        Write-Color -Text "You want to create ","$DataCenterAmount ","Datacenters. Is this correct?" -Color White,Yellow,White
        $result = $host.ui.PromptForChoice($title, $message, $options, 1)
            switch ($result){
                0{
                    Clear-Host
                    [System.Collections.ArrayList]$DatacenterArray = @()
                    $Curr = 1
                    While ($Curr -le $DataCenterAmount){ #Processes amount of datacenters to be created.
                        Write-Color -Text "Please enter the name of Datacenter ","$Curr",":" -Color White,Yellow,White
                        $DatacenterName = Read-Host
                        Clear-Host
                        Write-Color -Text "The name of Datacenter"," $Curr"," is"," $DatacenterName",". Is this correct?" -Color White,Yellow,White,Yellow,White
                        $result = $host.ui.PromptForChoice($title, $message, $options, 1)
                            switch ($result){
                                0{ #After confirmation of Datacenter name - creates datacenter
                                $folder = Get-Folder -NoRecursion
                                try {
                                New-Datacenter -Name $DatacenterName -Location $folder
                                }
                                catch{
                                    Clear-Host
                                    Write-Color -text "[WARNING] An error has occured during the Datacenter creation process, a connection error may have ocurred." -color red
                                    Read-Host "(Press 'Enter' to continue:)"
                                    $ChoiceTask = "Standard Check"
                                }
                                $DatacenterArray.Add($DatacenterName)
                                Clear-Host
                                Write-Color -Text "Datacenter"," $DatacenterName"," successfully created! (Press 'Enter' to continue)" -Color White,Yellow,White
                                Read-Host
                                $Curr++
                                Clear-Host
                                }
                                1{}
                            }
                    }
                $ChoiceTask = "Check Clusters"
                }#End 'Yes' Selection
                1{}
            }
    }

如您所见,它变得非常混乱。但重要的是用户要确保他们的选择是正确的。据我所知,这是提示是/否的最佳方式;但为了我自己,我真的想把它清理干净。如果您错过了上面的内容,这是与 VMware 的 PowerCLI 结合使用的,因此如果您不认识某些操作,这就是原因。并且 write-color 是一个自定义函数,用于简化屏幕上打印的变量的着色。尽管我相信还有一种更简单的方法可以做到这一点。

答案1

使用溅射传递长/大的参数集以增加可读性:

$splat = @{
  'Text' = ('The name of Datacenter ', $Curr, ' is ', $DatacenterName, '. Is this correct?')
  'Color' = (White,Yellow,White,Yellow,White)
}
Write-Color -Text $Text -Color $Color

考虑一个包装函数:

Function Ask-ColoredQuestion ($Text, $Color) {
   Write-Color -Text $Text -Color $Color
   $host.ui.PromptForChoice($title, $message, $options, 0)
}

$splat = @{
  'Text' = ('The name of Datacenter ', $Curr, ' is ', $DatacenterName, '. Is this correct?')
  'Color' = (White,Yellow,White,Yellow,White)
}

$Result = Ask-ColoredQuestion @splat

更好的是,文本颜色可以通过转义码来控制,转义码可以作为字符串的一部分。这将允许您使用或的内置-Prompt参数Read-Host$messagePromptForChoice()

$esc = "$([char]27)"
$Red = "$esc[31m"
$Green = "$esc[32m"
$message = '{0}{1} {2}{3}' -f $Red, 'Hello', $Green, 'World'
$message

在此处输入图片描述

因此,您可能需要重新使用Write-Color颜色转义码编写一个字符串,然后将该字符串传递给内置提示。

我认为这足以让你开始了!:D

答案2

我发现我做了很多是/否答案的提示,所以我写了一个函数来简化它。这可能会给你一些提示,但你可能想改进我的努力。

<#
.SYNOPSIS
    Prompts user for answer to a yes no prompt.
.DESCRIPTION
    The user is prompted with the argument, and asked for a reply.
    If the reply matches YES or NO (case insensitive) the value is true
    or false.  Otherwise, the user is prompted again.
#>
function ask-user {
    [CmdletBinding()]
    Param (
       [Parameter(Mandatory=$true)]
       [string] $question
    )
    Process {
       $answer = read-Host $question
       if ("YES","YE","Y" -contains $answer) {$true}
       elseif ("NO", "N" -contains $answer) {$false}
       else {ask-user $question}
    }
} # End function ask-user

相关内容