开发者

how to allow manual or automated choice in powershell?

I am writing a script where I want the users to e开发者_高级运维ither enter in a manual server or they could supply a list of servers from say c:\temp\servers.txt.

Only problem is that I have no idea how I make this happen - ie I know I could prompt the user to enter in the below - but I would like them to have a button choice or something - maybe they can type in a manual server or a path and then powershell figures out which is which?

Any idea how I go around this?

Read-Host "Do you wish to enter in a manual computer or list of computers? "

Thanks,


Look at PromptForChoice method. There are many resources on Internet. E.g. http://scriptolog.blogspot.com/2007/09/make-choice.html by @Shay.

First you have to show a prompt for choice (that's where you call PromptForChoice) and then process the user request (look at the switch at the page above).

Basically some sample code could be:

$choices = [Management.Automation.Host.ChoiceDescription[]] ( `
      (new-Object Management.Automation.Host.ChoiceDescription "&List","List of servers"),
      (new-Object Management.Automation.Host.ChoiceDescription "&One","One server"));
$answer = $host.ui.PromptForChoice("MicroTools","Run MicroTools?",$choices,0)
if ($answer -eq 0) {
  # get list of servers
} else {
  # get one server
}


Here is another solution given by advanced functions. Put the following code into serv.ps1

param ([Parameter(mandatory=$true)]$Servers)

foreach($server in $Servers)
{
  Write-Host $Server
}

When you call it with no arguments it prompt you :

PS C:\temp> .\serv.ps1

applet de commande serv.ps1 à la position 1 du pipeline de la commande
Fournissez des valeurs pour les paramètres suivants :
Servers: Mach1
Mach1

For more informations about available parameters :

Get-Help about_Functions_Advanced


You can also simply write a script that asks users to enter the servers as part of the script. Then try to check if the entered text is a filepath. If so, then get the content and treat that as a list of servers. Otherwise parse the entered text - for example let's assume the individual server names will be space separated.

The script would then look like this:

#Ask for servers (either space separated or file path)
write-host -noNewLine "Enter servers: "
$answer = read-host

#Process answer
if ($answer -eq $null)
{
    write-host -foregroundColor Red "Error: You have to specify servers."
    exit
}

if (Test-Path $answer)
{
    $servers = get-content $answer
}
else
{
    $servers = $answer.Split(" ")
}

#Print results
write-host "Result:"
$servers

Hope it helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜