如果条件不起作用,则为Powershell简单语法

时间:2017-02-15 13:06:00

标签: powershell if-statement dns conditional-statements

所以我正在尝试编写一个脚本,将DNS转发器设置为2个预设IP,但如果用户想要选择其他IP,他只需要在提示中给出它们。

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 个答案:

答案 0 :(得分:2)

对于那些不熟悉PowerShell的人来说,这是一个常见的错误。 PowerShell中的比较不是使用经典的运算符符号进行的;你必须使用“FORTRAN-style”运算符:

 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

答案 1 :(得分: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)