Maneiras de limpar meus prompts de sim/não no PowerShell

Maneiras de limpar meus prompts de sim/não no PowerShell

Então, para trabalhar, eles me deram esse script de "automação" que queriam empregar. Mas eu literalmente nunca escrevi nada no Powershell, então naturalmente reescrevi tudo do zero porque era um saque (não que o meu seja muito melhor), mas depois de 5 dias de experiência no Powershell, acho que fiz um progresso decente. No entanto, minhas solicitações de sim/não ficam bastante confusas e espero que as pessoas que realmente sabem o que estão fazendo aqui tenham algumas dicas para mim. Então aqui está meu código.

Estas são as declarações imediatas ...

    $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{}
            }
    }

Como você pode ver, fica muito confuso. Mas é importante que o usuário tenha certeza de que suas escolhas estão corretas. Pelo que posso dizer, esta é a melhor maneira de solicitar sim/não; mas eu gostaria de realmente limpar isso por minha causa. Se você perdeu o que foi dito acima, isso ocorre em conjunto com o PowerCLI da VMware, portanto, se você não reconhece algumas ações, é por isso. E write-color é uma função customizada para simplificar a coloração de variáveis ​​impressas na tela. Embora eu tenha certeza de que há uma maneira muito mais fácil de fazer isso também.

Responder1

UsarRespingospara passar conjuntos de parâmetros longos/grandes para aumentar a legibilidade:

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

Considere uma função wrapper:

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

Melhor ainda,a cor do texto pode ser controlada por meio de códigos de escape que podem fazer parte da sua string. Isso permitirá que você use o parâmetro embutido -Promptde Read-Hostou $messageemPromptForChoice()

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

insira a descrição da imagem aqui

Portanto, você pode querer refazer a ferramenta Write-Colorpara compor uma string com códigos de escape coloridos e, em seguida, passar essa string para os prompts integrados.

Acho que isso é o suficiente para você começar! :D

Responder2

Descobri que estava solicitando muitas respostas sim/não, então escrevi uma função para facilitar. Isso pode lhe fornecer algumas dicas, mas você pode querer melhorar meu esforço.

<#
.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

informação relacionada