在 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

相關內容