16

我对使用 PowerShell 很陌生,想知道是否有人对尝试让 PowerShell 函数返回值有任何意见。

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

 Function Something
 {
     # Do a PowerShell cmd here: if the command succeeded, return true
     # If not, then return false
 }

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

 Function OnlyTrue
 {
     # Do a PowerShell cmd here...
 }
4

4 回答 4

16

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

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

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

OnlyTrue

输出是Success文件是否存在,Fail如果不存在。

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

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

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

于 2013-08-09T15:00:57.470 回答
15

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

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

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

if (!(SuccessConnectToDB($connstr)) {
    exit  # "Failure Connecting"
}
于 2020-09-03T07:26:10.630 回答
7

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

Function Test-Something
 {
     Do-Something
     $?
 }

 Function OnlyTrue
 {
     if(Test-Something) { ... }
 }
于 2013-08-09T14:22:39.113 回答
3

非常延迟的答案,但在 powershell 5 中遇到了同样的问题。您可以使用 1 和 0 作为返回值。然后您可以将其转换为布尔值或仅使用“-eq 1”或 0

Function Test
{
   if (Test-Path c:\test.txt){
      return 0
   }else{
      return 1
   }
}

[bool](Test)
于 2019-04-04T12:20:49.353 回答