【问题标题】:How to catch exception so that exception message in not printed on console?如何捕获异常以使异常消息不在控制台上打印?
【发布时间】:2018-11-30 02:12:56
【问题描述】:

我有以下 cmdlet

function Service-Stop
{
  [cmdletbinding()]
  param(
  [Parameter(Mandatory=$true)][ValidateScript({$_ -match [IPAddress]$_ })][string]$Address,
  [Parameter(Mandatory=$true)][string]$Name,
  [Parameter(Mandatory=$true)][System.Management.Automation.PSCredential]$Credential
  )

  try
  {
    $wmi = Get-WmiObject -ComputerName $Address -Credential $Credential -Class Win32_Service -Filter "Name='$Name'"
    if($wmi)
    {
      $wmi.stopservice()
    }
  }
  catch
  {
    Write-Output "ErrorDetails: $_"
  }
}

我的理解是,每当调用Get-WmiObject 引发异常时,我的catch 块将被执行,然后我可以将输出通过管道传输到日志文件。问题是,当我从脚本中调用此 cmdlet 时,异常消息会显示在控制台上。

我不想那样。我希望在 catch 块中实现异常详细信息。

你能告诉我怎么做吗?

【问题讨论】:

  • 查看是否可以将异常记录到文件here
  • @VivekKumarSingh 我想禁止在控制台上打印异常消息。

标签: powershell


【解决方案1】:

我认为问题在于 Cmdlet Get-WmiObject 没有引发异常,而只是将其错误写入错误流并继续。即脚本的错误动作行为设置为“继续”。您可以通过传递给Get-WmiObjectErrorAction 参数来控制它:

$wmi = Get-WmiObject -ComputerName $Address -Credential $Credential -Class Win32_Service -Filter "Name='$Name'" -ErrorAction Stop

ErrorAction 的 stop 值表示您希望错误终止(通过引发异常)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2011-06-09
    相关资源
    最近更新 更多