Home > database >  IP address script is not correcting working with while and if statements
IP address script is not correcting working with while and if statements

Time:11-27

I am trying to write a script in to do 4 things:

Assign a static IP address (it's a small environment and historically been set up in this way). Rename the hostname. Add the PC to the domain and subsequently the appropriate OU. Add the primary user of the computer to the Remote Desktop group. I am trying to accomplish the first part of the above.

Can you please explain why this breaks the loop, shows errors from other if statements as well as the relevant one? It seems it doesn't correctly work.

Clear-Host

do 
{
  $ipvalid = 0
  $filsm = "192.168.0."
  $ip_entered = Read-Host 'Enter the host octet for the subnet 192.168.0.x'

  $ip = -join "$filsm$ip_entered"

  $ipexists = Test-Connection -ComputerName $ip -Quiet -Count 1

  if ( $ipexists -eq "" )
  { 
    $ipvalid  
  }
  else
  {  
  Write-Host "IP exists, enter another one"
  }

  if ($ip_entered -match "^\d $")
  { $ipvalid   }

  else 
  { Write-Host "Non-numeric character entered" }

  if ($ip_entered -ge 2 -and $ip_entered -le 254)
  { $ipvalid   }
  else
  { Write-Host "Enter a valid octet" }

 if ($ip_entered -ne $null)
  { $ipvalid   }
  else
  { Write-Host "No input entered" } 

} until ( $ipvalid -ge 3 )

CodePudding user response:

My first guess would be your $ip = -join "$filsm$ip_entered" is failing. Its proper syntax would be $result = 'item1','item2','item3' -join 'separator'. However, for what you are trying to accomplish $ip = "$filsm$ip_entered" is appropriate.

If I may also suggest a style change to use continue and break instead of incrementing a variable:

Clear-Host

while ($true)
{
  $filsm = "192.168.0."
  $ip_entered = Read-Host -Prompt 'Enter the host octet for the subnet 192.168.0.x'

  $ip = "$filsm$ip_entered"

  if ($ip_entered -EQ $null -Or $ip_entered -EQ "")
  {
     Write-Host "No input entered"
     continue
  }

  if ($ip_entered -NotMatch "^\d $")
  {
     Write-Host "Non-numeric character entered"
     continue
  }

  [int]$casted_entered = $ip_entered # should be fine as it was because it will compare string to string, but this shows your intent better
  if ($casted_entered -LT 2 -Or $casted_entered -GT 254)
  {
     Write-Host "Enter a valid octet"
     continue
  }

  if ( Test-Connection -ComputerName $ip -Quiet -Count 1 ) {
    Write-Host "IP exists, enter another one"
    continue
  }

  break
}

As a better, but perhaps more advanced alternative, you could use Write-Error and either $ErrorActionPreference = 'Stop' or (if you convert the loop into a function) -ErrorAction Stop.

  • Related