2017-02-15 78 views
0

所以我想寫一個腳本,將DNS轉發器設置爲2個預設的IP,但如果用戶想選擇其他IP,他只需要在提示中給他們。Powershell簡單的語法,如果條件不起作用

Write-Host " " 
Write-Host "DNS Forwarders are set on -192.168.20.3 & 168.192.24.3- want to choose these?" 

$Antw = Read-Host -Prompt 'y/n' 

If ($Antw.ToLower() = "n") 
{ 
    $ip1 = Read-Host -Prompt 'DNS Forwarder 1: ' 
    $ip2 = Read-Host -Prompt 'DNS Forwarder 2: ' 

    C:\Windows\System32\dnscmd.exe $hostname /resetforwarders $ip1, $ip2 
} 


     Elseif ($Antw.ToLower() = "y") 
     { 

      C:\Windows\System32\dnscmd.exe $hostname /resetforwarders 192.168.20.3, 168.192.24.3 

     } 


#Write-Host $Antw 

我的If/ElseIf似乎沒有工作,但如果我按'y',它仍然要求2 ip的?? ??我的代碼有什麼問題?

謝謝

回答

2

這是一個普遍的錯誤,那些不完全適合PowerShell的人。 PowerShell中的比較沒有使用經典的運算符符號來完成;您必須使用「FORTRAN式」運營商:

Write-Host " " 
Write-Host "DNS Forwarders are set on -192.168.20.3 & 168.192.24.3- want to choose these?" 

$Antw = Read-Host -Prompt 'y/n' 

If ($Antw.ToLower() -eq "n") 
{ 
    $ip1 = Read-Host -Prompt 'DNS Forwarder 1: ' 
    $ip2 = Read-Host -Prompt 'DNS Forwarder 2: ' 

    C:\Windows\System32\dnscmd.exe $hostname /resetforwarders $ip1, $ip2 
} 


     Elseif ($Antw.ToLower() -eq "y") 
     { 

      C:\Windows\System32\dnscmd.exe $hostname /resetforwarders 192.168.20.3, 168.192.24.3 

     } 


#Write-Host $Antw 
+0

非常感謝傑夫!我不知道-eq在PowerShell中用作比較方法。 –

+1

@KahnKah - 你會發現PowerShell自己的幫助文件非常有用 - 在一個提升的Powershell會話中,執行'Update-Help'命令,然後在任何Powershell會話中執行'Get-Help about_Comparison_Operators'。 'Get-Help'是可用的最有用的cmdlet之一。 –

2

比較運營商

-eq    Equal 
-ne    Not equal 
-ge    Greater than or equal 
-gt    Greater than 
-lt    Less than 
-le    Less than or equal 
-like   Wildcard comparison 
-notlike  Wildcard comparison 
-match   Regular expression comparison 
-notmatch  Regular expression comparison 
-replace  Replace operator 
-contains  Containment operator 
-notcontains Containment operator 
-shl   Shift bits left (PowerShell 3.0) 
-shr   Shift bits right – preserves sign for signed values. (PowerShell 3.0) 
-in    Like –contains, but with the operands reversed.(PowerShell 3.0) 
-notin   Like –notcontains, but with the operands reversed.(PowerShell 3.0)