我正在嘗試撰寫一個腳本來做 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 )
uj5u.com熱心網友回復:
我的第一個猜測是你$ip = -join "$filsm$ip_entered"失敗了。它的正確語法是$result = 'item1','item2','item3' -join 'separator'. 但是,對于您要完成的作業$ip = "$filsm$ip_entered"是合適的。
如果我也可以建議使用樣式更改continue而break不是增加變數:
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-Errorand 或者$ErrorActionPreference = 'Stop'or (如果您將回圈轉換為函式) -ErrorAction Stop。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/366551.html
上一篇:如何遠程呼叫.py腳本?
