IP 地址脚本未更正使用 while 和 if 语句

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

我正在尝试编写一个脚本来做 4 件事:

分配静态 IP 地址(这是一个小型环境,过去一直以这种方式设置)。 重命名主机名。 将 PC 添加到域,然后添加适当的 OU。 将计算机的主要用户添加到远程桌面组。 我正在努力完成上面的第一部分。

您能否解释一下为什么这会中断循环,显示其他 if 语句以及相关语句的错误?它似乎无法正常工作。

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 )

我的第一个猜测是您的 $ip = -join "$filsm$ip_entered" 失败了。它的正确语法是 $result = 'item1','item2','item3' -join 'separator'。但是,对于您要实现的目标,$ip = "$filsm$ip_entered" 是合适的。

如果我还建议更改样式以使用 continuebreak 而不是递增变量:

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
}

作为更好但可能更高级的替代方法,您可以使用 Write-Error$ErrorActionPreference = 'Stop' 或(如果将循环转换为函数)-ErrorAction Stop.