2017-02-15 61 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)