我是使用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...
}
发布于 2013-08-09 23:00:57
您可以在PowerShell中使用return语句:
Function Do-Something {
$return = Test-Path c:\dev\test.txt
return $return
}
Function OnlyTrue {
if (Do-Something) {
"Success"
} else {
"Fail"
}
}
OnlyTrue
输出为
如果文件存在并且
如果不是这样的话。
需要注意的是,PowerShell函数会返回所有未捕获的内容。例如,如果我将Do-Something的代码更改为:
Function Do-Something {
"Hello"
$return = Test-Path c:\dev\test.txt
return $return
}
那么返回结果总是成功的,因为即使文件不存在,Do-Something函数也会返回一个对象数组("Hello",False)。看一看
布尔值和运算符
有关PowerShell中的布尔值的更多信息。
发布于 2020-09-03 15:26:11
不要使用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"
}
发布于 2013-08-09 22:22:39
你会做这样的事。Test命令使用自动变量'$?‘。如果最后一个命令成功完成,则返回true/false (请参阅关于
_
自动
_
Variables主题了解更多信息):
Function Test-Something
{
Do-Something
$?
}
Function OnlyTrue
{
if(Test-Something) { ... }
}
https://stackoverflow.com/questions/18148560
复制相似问题