我怎样才能退出PowerShell的function

我有一个函数,我知道会抛出一个错误。 这个错误是预期的,但是当它被抛出时,我想结束这个函数。 我在脚本中有一个陷阱部分,我已经使用了ReturnBreak命令,但是他们没有做我想要的。 我在Begin {}Process {}部分都有陷阱声明。 我正在使用Get-WmiObject命令,并将-ErrorAction设置为stop 。 代码示例及其响应如下。

第一个例子w / return:

 Function Test { Param {"Some Parameters"} Begin {"Some beginning stuff"} process { Trap { Add-Content $($SomeFile) $($ComputerName + "is Not There") return } #End Trap Get-WmiObject Win32_NTLogEvent ` -ComputerName $ComputerName ` -Credential $Cred - ` -ErrorAction Stop }#End Process End {"Some ending things"} } #End Function 

这一个只是继续下去,而不退出function。

第二个例子w / break:

 Function Test { Param {"Some Parameters"} Begin {"Some beginning stuff"} process { Trap { Add-Content $($SomeFile) $($ComputerName + "is Not There") Break } #End Trap Get-WmiObject Win32_NTLogEvent ` -ComputerName $ComputerName ` -Credential $Cred - ` -ErrorAction Stop }#End Process End {"Some ending things"} } #End Function 

这一个退出整个脚本。

我环顾四周,但我找不到任何具体的退出function。 还有更多的function,包括另一个Get-WmiObject命令。 如果第一个Get-WmiObject不能联系计算机,我希望它退出函数。 我不能使用pingtesting,因为许多服务器阻塞ICMP。

$? varible可以很好地捕捉错误。 它包含最后执行的命令的布尔值。 如果命令没有错误$? = $true被执行$? = $true $? = $true$? 当最后执行的命令出错时,将会是$false

创build一个布尔值,每次在发生错误的命令后都被设置。 假设这里的命令是get-wmiObject:

 $running = $true While ($running) { Get-WmiObject Win32_NTLogEvent -ComputerName $ComputerName -Credential $Cred $running = $? } 

既然你可能在你的循环中有一个条件,它会看起来像while(<condition> -and $running)

如果你想添加你的错误信息,只需要抛出一些东西,像这样设置后运行

 if(!$running){Add-Content $($SomeFile) $($ComputerName + "is Not There") } 

返回实际上没有帮助,但是可以使用break,唯一的要求就是按照devise使用它 – 摆脱循环… 🙂

这里的诀窍是构build一个简单的循环,无论如何,只要运行一次,就可以在循环中使用break:

 # Script body... do { Test-WithBreak } until ($true) # Other operations you want to perform even if Test-WithBreak breaks. 

其原因是,break是循环指令,在PowerShell中它并不关心任何限制(因此,在脚本中打破,从脚本运行,从脚本运行将能够一路走下去,杀死整个事物,除非find一些循环来阻止他)。

我前一阵子在这个问题上发表了博文 。

尝试“继续”作为关键字

陷阱[例外] {“在PowerShell”}