Search code examples
powershellpowershell-remoting

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?


Solution

  • 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