
Entonces, para trabajar, me dieron este script de "automatización" que querían emplear. Pero literalmente nunca escribí nada en Powershell, así que, naturalmente, reescribí todo desde cero porque era un botín (no es que el mío sea mucho mejor), pero después de 5 días de experiencia en Powershell creo que he logrado un progreso decente. Sin embargo, mis indicaciones de sí/no se vuelven bastante confusas y espero que las personas que realmente saben lo que están haciendo aquí tengan algunos consejos para mí. Así que aquí está mi código.
Estas son las prontas declaraciones...
$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 puedes ver, se vuelve realmente complicado. Pero es importante que el usuario se asegure de que sus elecciones sean correctas. Por lo que puedo decir, esta es la mejor manera de responder sí/no; pero realmente me gustaría limpiar esto por mi bien. Si se perdió lo anterior, esto está en conjunto con PowerCLI de VMware, por lo que si no reconoce algunas acciones, ese es el motivo. Y write-color es una función personalizada para simplificar la coloración de las variables impresas en la pantalla. Aunque estoy seguro de que también hay una manera mucho más sencilla de hacerlo.
Respuesta1
UsarSalpicaduraspara pasar conjuntos de parámetros largos/grandes para aumentar la legibilidad:
$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 una función contenedora:
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
Aun mejor,El color del texto se puede controlar mediante códigos de escape que pueden ser parte de su cadena.. Esto le permitirá utilizar el parámetro incorporado -Prompt
de Read-Host
o $message
enPromptForChoice()
$esc = "$([char]27)"
$Red = "$esc[31m"
$Green = "$esc[32m"
$message = '{0}{1} {2}{3}' -f $Red, 'Hello', $Green, 'World'
$message
ingrese la descripción de la imagen aquí
Por lo tanto, es posible que desee volver a utilizar las herramientas Write-Color
para componer una cadena con códigos de escape de colores y luego pasar esa cadena a las indicaciones integradas.
¡Creo que eso es suficiente para empezar! :D
Respuesta2
Descubrí que estaba haciendo muchas indicaciones para respuestas de sí o no, así que escribí una función para hacerlo más fácil. Esto puede brindarle algunos consejos, pero es posible que desee mejorar mi esfuerzo.
<#
.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