如何退出PowerShell中的try-catch块?

Gre*_*SAT 0 powershell try-catch

我想从try块内退出:

function myfunc
{
   try {
      # Some things
      if(condition) { 'I want to go to the end of the function' }
      # Some other things
   }
   catch {
      'Whoop!'
   }

   # Other statements here
   return $whatever
}
Run Code Online (Sandbox Code Playgroud)

我用a测试过break,但这不起作用.如果任何调用代码在循环内,它会打破上层循环.

Rom*_*min 9

一个额外的脚本块try/catchreturn它内部可能会这样做:

function myfunc($condition)
{
    # Extra script block, use `return` to exit from it
    .{
        try {
            'some things'
            if($condition) { return }
            'some other things'
        }
        catch {
            'Whoop!'
        }
    }
    'End of try/catch'
}

# It gets 'some other things' done
myfunc

# It skips 'some other things'
myfunc $true
Run Code Online (Sandbox Code Playgroud)

  • 没有点它不应该工作(在这种情况下,函数创建并输出脚本块).点运算符调用当前作用域中的脚本.还有`&`.它可以用于新范围中的调用(例如,为了从函数的其余部分隐藏一些内部变量). (3认同)
  • 至于*技巧*......好吧,PowerShell本身并没有提供任何退出`try/catch`的东西。 (2认同)
  • @Shay Levy - 这将是"从整个函数返回",而不是"转到try/catch的结尾". (2认同)