
그래서 업무를 위해 그들은 나에게 그들이 사용하고 싶은 "자동화" 스크립트를 주었습니다. 하지만 저는 말 그대로 Powershell에서 아무것도 작성한 적이 없기 때문에 자연스럽게 모든 것을 처음부터 다시 썼습니다. 그것이 전리품이었기 때문입니다(내 것이 훨씬 낫다는 것은 아닙니다). 하지만 Powershell을 5일 동안 경험한 후에는 상당한 진전을 이룬 것 같습니다. 그러나 내 예/아니요 프롬프트는 상당히 지저분해지며 여기서 자신이 무엇을 하고 있는지 실제로 아는 사람들이 나에게 몇 가지 팁을 주길 바랍니다. 여기 내 코드가 있습니다.
이는 신속한 선언입니다...
$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
.$message
PromptForChoice()
$esc = "$([char]27)"
$Red = "$esc[31m"
$Green = "$esc[32m"
$message = '{0}{1} {2}{3}' -f $Red, 'Hello', $Green, 'World'
$message
Write-Color
따라서 색상 이스케이프 코드로 문자열을 구성한 다음 해당 문자열을 내장 프롬프트에 전달하도록 도구를 다시 사용할 수 있습니다 .
시작하기에 충분하다고 생각합니다! :디
답변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