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

时间:2012-11-03 17:18:38

标签: 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
}

我使用break进行了测试,但这不起作用。如果任何调用代码在循环内,它会打破上层循环。

3 个答案:

答案 0 :(得分:9)

try/catch周围的额外脚本块和其中的return可能会执行此操作:

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

答案 1 :(得分:2)

做你想做的事情的规范方法是否定条件并将“其他事物”放入“当时”块。

function myfunc {
  try {
    # some things
    if (-not condition) {
      # some other things
    }
  } catch {
    'Whoop!'
  }

  # other statements here
  return $whatever
}

答案 2 :(得分:1)

你可以这样做:

function myfunc
{
   try {
      # Some things
      if(condition)
      {
          goto(catch)
      }
      # Some other things
   }
   catch {
      'Whoop!'
   }

   # Other statements here
   return $whatever
}