$ _。异常是$ null,当在呼叫中使用–为什么?

发布于 2025-02-10 01:52:39 字数 364 浏览 3 评论 0 原文

我有一个包含以下记录函数的powershell脚本:

function LogError([string] $message, $exception = $null) {…}

在try-catch块中,当发生异常时,我称之为以下记录函数:

catch { LogError("…", $_.Exception) }

logerror 函数中,第二个参数始终为 $ null 。为什么?

我找不到任何文档,可以解释为什么我不能在函数调用中使用 $ _。异常,或者我应该使用。

I have a PowerShell script containing the following logging function:

function LogError([string] $message, $exception = $null) {…}

In a try-catch block, when an exception occurs, I call that logging function like this:

catch { LogError("…", $_.Exception) }

In the LogError function, the second argument is always $null. Why?

I couldn't find any documentation that would explain why I cannot use $_.Exception in a function call or that I am supposed to use instead.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦中楼上月下 2025-02-17 01:52:39

PowerShell函数参数未使用括号 /逗号格式传递。

那是不好的

LogError("…", $_.Exception)

powershell将其视为一个单一的阵列参数。
这实际上与 logerror -message(“ ...”,$_。例外)

LogError '…' $_.Exception

是最好的

 LogError -message '...' -exception $_.Exception

完成工作示例

function LogError([string] $message, $exception = $null) {
  Write-Host $message
   $exception | Out-String | Write-Host -ForegroundColor red 
  }

try {
  throw 'Noooo !!!!'
}
catch {
  LogError -message 'oops' -exception $_.Exception
}

Powershell function arguments are not passed using the parenthesis / comma formatting.

That is bad

LogError("…", $_.Exception)

Powershell take that as a single array argument.
This is actually the same as LogError -Message ("...",$_.Exception)

That is ok

LogError '…' $_.Exception

That is best

 LogError -message '...' -exception $_.Exception

Complete working example

function LogError([string] $message, $exception = $null) {
  Write-Host $message
   $exception | Out-String | Write-Host -ForegroundColor red 
  }

try {
  throw 'Noooo !!!!'
}
catch {
  LogError -message 'oops' -exception $_.Exception
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文