Windows Powershell where对象返回代码
很长一段时间后,我将从bash返回powershell,我发现where对象行为非常混乱 为什么以下代码段返回成功?什么也没找到!为什么这不会像grep那样返回失败Windows Powershell where对象返回代码,windows,powershell,error-handling,exit-code,Windows,Powershell,Error Handling,Exit Code,很长一段时间后,我将从bash返回powershell,我发现where对象行为非常混乱 为什么以下代码段返回成功?什么也没找到!为什么这不会像grep那样返回失败 C:> Get-Process | ?{$_.name -like "laksdjfajsdfkjasdkf"} C:> echo $? True tl;dr # Run the command and, in addition to outputting to the console, # collect the r
C:> Get-Process | ?{$_.name -like "laksdjfajsdfkjasdkf"}
C:> echo $?
True
tl;dr
# Run the command and, in addition to outputting to the console,
# collect the results in variable $result, via common parameter -OutVariable / -ov
# If you do NOT need to output to the console, simply use:
# $result = Get-Process | ...
Get-Process | ? { $_.name -like "laksdjfajsdfkjasdkf" } -ov result
# Test if the result is empty (using implicit Boolean conversion)
if (-not $result) { Write-Warning "Nothing matched." }
PowerShell中的自动(布尔)
$?
变量不是传统Shell中退出代码的(抽象)等价物,正如PetSerAl指出的那样
$?
只告诉您最后一条语句是否成功,以及围绕它的规则非常复杂,如图所示。成功意味着没有发生错误,根据该定义,不返回任何内容的筛选操作是成功的。
简而言之:
$?
在PowerShell中用处有限。
但是,最近执行的外部程序的退出代码反映在自动变量$LASTEXITCODE
中,因此如果您实际调用了grep
,其退出代码将反映在那里。(如果退出代码为
0
或$False
,则在执行外部程序后立即设置$?
,以反映$True
,否则,$?
可能在语句完成时已经反映了其他内容,具体取决于语句的细节,例如将调用包含在内)<代码>(…))
在本例中,您希望确定调用Where Object
cmdlet(通过其内置别名?
调用)执行的过滤操作是否返回了任何匹配项,但在PowerShell中,该状态不会单独反映在任何地方因此,您必须检查输出本身,以确定是否有匹配的内容,如顶部的代码段所示 此场景中没有错误,但为了完整起见: PowerShell的错误处理非常复杂,但与传统shell不同;您可以找到。这可能会有所帮助:PowerShell cmdlet不像本机可执行文件那样具有返回代码。如果没有
错误记录
,它将无法返回故障。