
Итак, для работы они дали мне этот скрипт "автоматизации", который они хотели использовать. Но я буквально никогда ничего не писал в 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{}
}
}
Как видите, все становится очень запутанным. Но важно, чтобы пользователь убедился, что его выбор правильный. Насколько я могу судить, это лучший способ получить подсказку «да/нет»; но я бы хотел действительно очистить это для себя. Если вы пропустили вышесказанное, это связано с PowerCLI VMware, так что если вы не узнаете некоторые действия, вот почему. А 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
или $message
вPromptForChoice()
$esc = "$([char]27)"
$Red = "$esc[31m"
$Green = "$esc[32m"
$message = '{0}{1} {2}{3}' -f $Red, 'Hello', $Green, 'World'
$message
введите описание изображения здесь
Поэтому вам, возможно, захочется переделать инструмент, Write-Color
чтобы составить строку с цветными escape-кодами, а затем передать эту строку встроенным подсказкам.
Думаю, этого достаточно для начала! :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