简体   繁体   中英

powershell read-host into range operator

I'm trying to find a way to have a variable that has a read-host where you can enter numbers in a range operator format.

I essentially want to do the following

$domain=Domain.Host    
$Servers = Read-Host "What servers do you want to check?" #this is where a user would input @(1..10)
$CompleteServer = $Servers$Domain
Get-Service -ComputerName $CompleteServer -Name "Service Name"

So $CompleteServer would contain

01.domain.host

02.domain.host

...

10.domain.host

Is this at all possible, to atleast even have a read-input go into a range operator?

You can use Invoke-Expression , but be careful to validate the input:

$UserInput = 
Read-Host 'Enter a number range (eg. 1..5)'

If ($UserInput -match '^\d+\.\.\d+$')
  { $NumberRange = Invoke-Expression $UserInput }
  Else { Write-Host 'Input not in correct format.' }

$NumberRange

Enter a number range (eg. 1..5): 2..6
2
3
4
5
6

Read-Host only reads strings, I think.

If you want them to input a list, you can let them to separate input by commas or space.

For Example

$input = Read-Host 'enter input, separated by commas'
$inputList = $input -split ','

or

$input = Read-Host 'enter input, separated by space'
$inputList = $input -split ' '

if user needs to enter a long string you might want them to input with newlines or stuff:

$inputList = @()
Write-Host 'enter your input, when you finish one item, press enter, if you finish all the items, enter "END" and press enter'
$input = Read-Host 'enter the input'
while(input -nq 'END') {
     $inputs.Add(input)
     $input = Read-Host 'enter the input'
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM