windows - 是否可以只为 catch block 创建一个函数?

标签 windows powershell powershell-remoting

我有多个 try catch block ,它们都使用相同的 catch block 。

    try {   
        invoke-command -cn $host -Credential $cred -ScriptBlock {
        param($name)    
        statement...
        } -ArgumentList $name
        
    } catch {
        $formatstring = "{0} : {1}`n{2}`n" +
                    "    + CategoryInfo          : {3}`n" +
                    "    + FullyQualifiedErrorId : {4}`n"
        write-host ($formatstring)
        exit 1
    }

...

    try {   
    another statement...
        
    } catch {
        $formatstring = "{0} : {1}`n{2}`n" +
                    "    + CategoryInfo          : {3}`n" +
                    "    + FullyQualifiedErrorId : {4}`n"
        write-host ($formatstring)
        exit 1
    }

我想问一下是否可以创建一个具有 catch block 的函数,这样我就可以调用和使用该函数而不是编写相同的 catch block 多次。

我正在使用 poweshell 5

最佳答案

catch需要一个 literal { ... } block 来跟随它,但是从 inside 该 block 您可以自由调用可重用代码,例如一个函数,或者在最简单的情况下,一个 script block :

# Define a script block to use in multiple `catch` blocks.
$sb = {
  "[$_]" # echo the error message
}

# Two simple sample try / catch statements:

try {
  1 / 0
}
catch {
  . $sb # `. <script-block>` invokes the block directly in the current scope
}

try {
  Get-Item -NoSuchParam
}
catch {
  . $sb
}

注意:.dot-sourcing operator , 用于调用脚本 block 直接在当前范围,允许您直接修改该范围的变量。这使得脚本 block 的行为就像直接用作 catch black 一样。

相比之下,如果您想在 child scope 中执行脚本 block ,使用 &call operator .

关于windows - 是否可以只为 catch block 创建一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71476295/

相关文章:

powershell - 复制时拒绝访问

c++ - 添加目录路径 Windows 8.1

c++ - 组合位图 - GDI/GDI+?

node.js - 错误! addLocal 无法在 Windows 中安装

powershell - 使用 PowerShell DSC 获取 AWS S3 存储桶对象

powershell - Get-AzureWebsiteLog -Tail 不起作用

function - 函数构建的搜索结果过多

powershell - 如何在freebsd上安装 "Powershell"?

windows - Windows Hook 的 Linux 等价物

powershell - Azure VM 设置中的 DefaultWinRMCertificateThumbprint 字段为空