powershell如何判断用户输入是否包含以80结尾的数字

时间:2016-12-09 20:06:18

标签: powershell

我有一个变量包含数字,例如

$port = 3480

如果端口号最后包含80,我如何使用 if else 条件

if ($port -contains 80)
{
    "true"
}
else
{
    "false"
}

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

$port = 180

#with like operator
if ($port -like "*80")
{
    Write-Host "true 1"
}

#with regex
if ($port -match "\d{0,}80$")
{
    Write-Host "true 2"
}

#with endwith of string
if ($port.ToString().EndsWith("80"))
{
    Write-Host "true 3"
}

#with modulo math
if (($port - 80) % 100 -eq 0)
{
    Write-Host "true 4"
}

#with substring
if ($port.ToString().Length -ge 2 -and $port.ToString().Substring($port.ToString().Length -2) -eq "80")
{
    Write-Host "true 5"
}

# with fool method 1
if (($port -split "")[-2..-3] -join "" -eq "08")
{
    Write-Host "true 6"
}

#with fool method 2
if (($port -split "" | select -Last 3) -join "" -eq "80")
{
    Write-Host "true 7"
}

#imagine your methode... :)

答案 1 :(得分:0)

$port = read-host -prompt "Please enter your port number"
If ($port -like "*80") {
    $TRUE
} else {
    $FALSE
}

这里发生了什么:

  1. $ Port变量接收并存储询问问题的答案
  2. 如果$ Port类似于以80结尾的任何内容,那么它将返回$ TRUE
  3. 如果$ Port不以80结尾,那么它将等于$ FALSE。