powershell - 我的 if 语句有问题吗?

标签 powershell if-statement

一个令人困惑的问题。

$msg = 'http://www.bla.de'

$match = $msg -match '^(.*)".+?":(\S+)\s*(.*)$'
$match_linkalone = $msg -match '^(.*)(http://|https://)(\S+)\s*(.*)$'

$match
> False
$match_linkalone
> True

if($match -eq "True" -and $match_linkalone -eq "False")
    {echo 'if';}
        elseif($match_linkalone -eq "True" -and $match -eq "False")
            {echo 'elif';}
                else
                    {echo 'else';}
> else

但如果我这样做

$match = 'False'
$match_linkalone = 'True'

if($match -eq "True" -and $match_linkalone -eq "False")
    {echo 'if';}
        elseif($match_linkalone -eq "True" -and $match -eq "False")
            {echo 'elif';}
                else
                    {echo 'else';}
> elif

这个我实在是看不懂……

何时 $match = False$match_linkalone = True通过 -match 定义,那么它应该会遇到我的 elseif陈述。但它会转到else我不知道为什么......但是当我手动将文本放入两个变量中时它就起作用了。

我正在使用 PowerShell

最佳答案

您的变量 $match$match_linkalone 包含 bool 值,但您将它们与字符串进行比较。在类似 PowerShell automatically converts 的比较中将第二个操作数转换为与第一个操作数匹配的类型。空字符串转换为 bool 值时变为 $false,非空字符串转换为 $true

基本上你的表达式是这样评估的:

$match -eq "True" -and $match_linkalone -eq "False"
$false -eq $true -and $true -eq $true
$false -and $true
$false

将第二个操作数更改为 bool 值:

if ($match -eq $true -and $match_linkalone -eq $false)

或者(更好)完全删除比较,因为您的变量已经包含 bool 值:

if ($match -and -not $match_linkalone)

问题就会消失。

关于powershell - 我的 if 语句有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31849239/

相关文章:

PowerShell:当 .ctor 只有一个类型为 List<T> 的参数时,无法找到正确的 .ctor

powershell - 使用Powershell Windows 2008导出特定进程

powershell - 使用 PowerShell 时间跨度的算术

Azure 函数(PowerShell)

python - 在 if 语句中中断 for 循环

javascript - 使用 Javascript 通过 if 语句更改样式表?

linux - Bash读取txt文件并存储在数组中

bash - 需要 Powershell base64 编码

batch-file - 批处理文件,如果语句被跳过

java - 检查线程是否为 null 的方法(在 Java 中),操作数位置是否有所不同