开始记录和记录批处理文件输出

Xan*_*rim 6 powershell logging module batch-file transcription

我在 PowerShell 模块中有一个函数,它创建一个日志文件并使用该文件启动转录(见下文)。运行 PowerShell 脚本时,这非常有效并捕获所有输出。

运行调用批处理文件的 PowerShell 脚本时(我们在从 CMD > PowerShell 迁移时经常这样做),批处理文件输出显示在与 PowerShell 脚本相同的窗口中的控制台上,但转录日志文件仅显示 1 个空白调用批处理文件的行。

09:53:25 AM [Success] Zip file already up to date, no need to download!
09:53:25 AM [Note   ] Calling 1.bat

10:07:55 AM [Note   ] Calling 2.bat
Run Code Online (Sandbox Code Playgroud)

我从 .ps1 脚本调用批处理文件,仅使用与号“&”。

奇怪的是,有时批处理文件输出被捕获在日志中(通常是调用的第一个批处理文件)。但是我找不到这些文件的任何特别之处。

同样奇怪的是,有时我们调用外部程序(WinSCP),而这些命令的输出有时只显示在脚本中。可能相关。

作为参考,这里是我用来创建流程记录的函数。

Function Log_Begin()
{
    <#
    .SYNOPSIS
    Starts the process for logging a PowerShell script.
    .DESCRIPTION
    Starts the process for logging a PowerShell script. This means that whenever
    this function is called from a PowerShell script, a folder called 'Logs' will
    be created in the same folder, containing a full transcript of the script's output.
    .EXAMPLE
    C:\PS> Log_Begin
    #>
    Process
    {
        $ScriptLoc = $MyInvocation.PSCommandPath
        $WorkDir = Split-Path $ScriptLoc
        If (!(Test-Path "$WorkDir\Logs")) {mkdir "$WorkDir\Logs" | Out-Null}
        $LogPath = "$WorkDir\Logs"
        $ScriptName = [io.path]::GetFileNameWithoutExtension($ScriptLoc)
        $LogDate = Get-Date -format "yyyy-MM-dd"
        $LogName = "$ScriptName $LogDate.log"
        $global:Log = $LogPath + "\" + $LogName
        $ErrorActionPreference="SilentlyContinue"
        Stop-Transcript | out-null
        $ErrorActionPreference = "Continue"
        # Create file and start logging
        If (!(Test-Path $Log)) {
            New-Item -Path $Log -ItemType File | Out-Null
        }
        Start-Transcript -Path $Log -Append
    }
}
Run Code Online (Sandbox Code Playgroud)

有人对如何捕获批处理文件输出有任何想法吗?最好我不必更改脚本中对批处理文件的每个调用,并在模块中进行某些操作。