在自定义 powershell 函数中模拟 -ErrorAction [英] Emulating -ErrorAction in custom powershell function

查看:50
本文介绍了在自定义 powershell 函数中模拟 -ErrorAction的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在自定义 powershell 函数中模拟 -ErrorAction.例如考虑以下脚本

函数 Foo2{写主机在 Foo2"#...发生错误Foo3}函数 Foo1{写主机在 Foo1"Foo2}函数 Foo3{写主机在 Foo3"}

PS>Foo1 -ErrorAction 停止

是否可以在 Foo2 发生错误时停止 Foo1 的执行,而不继续执行 Foo3 ?

解决方案

get-help about_Functions_CmdletBindingAttribute

你想要:

<前>函数 Foo1() {[CmdletBinding()]参数()过程{写主机在 Foo1"Foo2}}

这与仿真无关,它意味着真正在您的函数中实现通用参数;如果这是你的意图.

<小时>

之后,你可以这样工作:

<前>Foo1 -ErrorAction 停止

您可以对 Foo2Foo3 使用相同的语法.

<小时>

要记录错误,请照常使用重定向.

How to emulate -ErrorAction in custom powershell function. For example consider the following script

function Foo2
{
  Write-Host "in Foo2"
  #...Error occurs 
  Foo3
}

function Foo1
{
   Write-Host "in Foo1"
   Foo2
}

function Foo3
{
   Write-Host "in Foo3"
}

PS>Foo1 -ErrorAction stop

Is it possible to stop the execution of Foo1 when error occurs in Foo2, instead of proceeding with execution of Foo3 ?

解决方案

get-help about_Functions_CmdletBindingAttribute

You want:

function Foo1() {
 [CmdletBinding()]
 PARAM()
 process{
   Write-Host "in Foo1"
   Foo2
 }
}

This is not about emulation, it means really implementing common parameters in your function; if this was your intention.


After that, you can work like this:

Foo1 -ErrorAction stop

You can use the same syntax for Foo2 and Foo3.


To log error use redirection as usual.

这篇关于在自定义 powershell 函数中模拟 -ErrorAction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆