如何在异常之前捕获返回

jgr*_*012 2 powershell exception return-value

是否有可能捕获由函数创建的输出,这也会导致异常?

function functionWhichCreatesOutputThenCausesAnException() {
    "hello"
    1/0
    "world"
}

try { 
    $result = functionWhichCreatesOutputThenCausesAnException 
} catch {
    $($error[0])
}
Run Code Online (Sandbox Code Playgroud)

我的功能创建的输出显示在我的终端中.我想捕捉"你好".这可能吗?

mjo*_*nor 5

这似乎有效:

function functionWhichCreatesOutputThenCausesAnException() {
    "hello"
    1/0
    "world"
}

try { 
    $result = @()
    functionWhichCreatesOutputThenCausesAnException | foreach {$result += $_}
} catch {
    $($error[0])
}
Run Code Online (Sandbox Code Playgroud)