PowerShell注销输出在try/Catch Block中不起作用



以下是我的powershell环境(通过get-host命令):

Name             : Windows PowerShell ISE Host
Version          : 5.1.15063.608
InstanceId       : 46c51405-fc6d-4e36-a2ae-09dbd4069710
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.Host.ISE.ISEOptions
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

我有一个向资源提出休息请求的脚本 - 一切正常。

测试时,我将URL更改为无效,以查看是否将错误消息写入输出文件 - 这是我感到困惑的地方。看来,通过使用写入者,为日志编写异常的唯一方法。当我使用写入输出时,异常消息永远不会写入日志文件。以下是我正在使用的代码:

function rest_request( $method, $uri )
{
   # Code here create @req dictionary
   try {
      $json = Invoke-RestMethod @req 
   } catch {
      # If using Write-Output - Nothing is written to output file???
      # MUST use Write-Host for error info to be included in output file - WHY?
      Write-Host "* REST Request Error:"
      Write-Host $error[0] | Format-List -force
      $json = $null
   }
   return $json
}
function do_something()
{
    Write-Output "Start..."
    # other functions called here but removed for clarity.
    # The other functions contain Write-Output statements
    # which are showing in the log file.
    # Issue REST request with invalid URL to cause exception ...
    $json = rest_request "Get" "https://nowhere.com/rest/api" 
    Write-Output "Done."
}
do_something | Out-File "D:templog_file.txt" -Append

根据此博客文章:应该避免使用写入主持人,但是,看来写入主持人是我在输出文件中获取错误消息的唯一方法。

我的问题是:您如何编写一个函数,该函数发出休息请求并在成功时返回结果,但是如果发生错误,请将错误消息写入输出文件并返回$ null?

当我对PowerShell方面相当绿色,任何建议都将不胜感激。

好的 - 我完全放弃了重定向,而是编写了将参数写入日志文件的函数,如下:

function log_write
{ 
   param
   (
      [Parameter(ValueFromPipeline=$true)] $piped
   )
   $piped | Out-File $log_file -Append
}

注意:$ log_file是在初始化时设置的,因为我需要一周中的每一天的新日志文件名。

然后,我用log_write替换了所有书面输出/写入主持人,即:

log_write "* REST Request Error:"
$s = $error[0] | Format-List -force
log_write $s

工作就像魅力一样,异常消息写入日志文件,而没有任何一个问题。

据我所知,Write-Host仅写给主机,别无其他。

在您的示例中,do_something没有返回任何内容,因此难怪您在日志文件中没有任何东西。

这是您可以做到的,但是存在许多不同的方法:

function Send-RESTRequest {
    Param($method, $uri, $logFile)
    # Code here create @req dictionary
    try {
        # make sure exception will be caught
        $json = Invoke-RestMethod @req -ErrorAction Stop
    } catch {
        # send exception details to log file
        $_ | Out-File $logFile -Append
        $json = $null
    }
    return $json
}
function Do-Something {
    # Issue REST request with invalid URL to cause exception ...
    $json = Send-RESTRequest -method "Get" -uri "https://nowhere.com/rest/api" -logFile "D:templog_file.txt"
}
Do-Something

最新更新