PowerShell函数返回true/false

sca*_*t17 8 powershell function return-value

我是使用PowerShell的新手,并想知道是否有人会尝试让PowerShell函数返回值.

我想创建一些将返回值的函数:

 Function Something
 {
     # Do a PowerShell cmd here: if the command succeeded, return true
     # If not, then return false
 }
Run Code Online (Sandbox Code Playgroud)

然后有第二个函数只有在上面的函数为真时才会运行:

 Function OnlyTrue
 {
     # Do a PowerShell cmd here...
 }
Run Code Online (Sandbox Code Playgroud)

Jer*_*son 11

不要使用 True 或 False,而是使用 $true 或 $false

function SuccessConnectToDB {
 param([string]$constr)
 $successConnect = .\psql -c 'Select version();' $constr
    if ($successConnect) {
        return $true;
    }
    return $false;
}
Run Code Online (Sandbox Code Playgroud)

然后以一种干净的方式调用它:

if (!(SuccessConnectToDB($connstr)) {
    exit  # "Failure Connecting"
}
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案 (3认同)

ant*_*oni 8

您可以在PowerShell中使用return语句:

Function Do-Something {
    $return = Test-Path c:\dev\test.txt
    return $return
}

Function OnlyTrue {
    if (Do-Something) {
        "Success"
    } else {
        "Fail"
    }
}

OnlyTrue
Run Code Online (Sandbox Code Playgroud)

Success如果文件存在Fail则输出,如果不存在则输出.

需要注意的是,PowerShell函数会返回未捕获的所有内容.例如,如果我将Do-Something的代码更改为:

Function Do-Something {
    "Hello"
    $return = Test-Path c:\dev\test.txt
    return $return
}
Run Code Online (Sandbox Code Playgroud)

然后返回将始终为Success,因为即使文件不存在,Do-Something函数也会返回一个对象数组("Hello",False).有关PowerShell 中布尔值的更多信息,请查看布尔值和运算符.

  • 对于未来的读者,我陷入了警告。我期望我的函数返回“$false”,但我总是收到“@($false,$false)”。这是因为我没有将一个函数调用的输出捕获到变量中。 (2认同)

Sha*_*evy 5

你会做这样的事情.Test命令使用自动变量'$?'.如果最后一个命令成功完成,则返回true/false(有关更多信息,请参阅about_Automatic_Variables主题):

Function Test-Something
 {
     Do-Something
     $?
 }

 Function OnlyTrue
 {
     if(Test-Something) { ... }
 }
Run Code Online (Sandbox Code Playgroud)