powershellfileloggingimport-module

How to log output of imported PowerShell module to a log file


I have a PowerShell Script that is importing a module and I am calling this module. However, this module has lots of useful output that I am not capturing and I would like to write it to a file. What is the best way to do this?

Example code:

Write-Host "Loading modules.." -ForegroundColor Cyan

Import-Module C:\Users\Dev1\Downloads\WimConvertTest\WindowsImageTools\private\cleanupFile.ps1
Import-Module C:\Users\Dev1\Downloads\WimConvertTest\WindowsImageTools\private\Get-FullFilePath.ps1
Import-Module C:\Users\Dev1\Downloads\WimConvertTest\WindowsImageTools\private\Initialize-DiskPartition.ps1
Import-Module C:\Users\Dev1\Downloads\WimConvertTest\WindowsImageTools\private\Initialize-VHDPartition.ps1
Import-Module C:\Users\Dev1\Downloads\WimConvertTest\WindowsImageTools\private\MountVHDandRunBlock.ps1
Import-Module C:\Users\Dev1\Downloads\WimConvertTest\WindowsImageTools\private\New-TemporaryDirectory.ps1
Import-Module C:\Users\Dev1\Downloads\WimConvertTest\WindowsImageTools\private\Run-Executable.ps1
Import-Module C:\Users\Dev1\Downloads\WimConvertTest\WindowsImageTools\private\Set-DiskPartition.ps1
Import-Module C:\Users\Dev1\Downloads\WimConvertTest\WindowsImageTools\private\Set-VHDPartition.ps1
Import-Module C:\Users\Dev1\Downloads\WimConvertTest\WindowsImageTools\private\Wim2VhdClass.ps1
Import-Module C:\Users\Dev1\Downloads\WimConvertTest\WindowsImageTools\private\cleanupFile.ps1
Import-Module C:\Users\Dev1\Downloads\WimConvertTest\WindowsImageTools\Public\Convert-Wim2VHD.ps1

try
{
    Write-Host "========================== Creating VHDX ================================== "
    Convert-WIM2VHD -Path ".\os_1.vhdx" -SourcePath ".\os_1.wim" -Size 16GB -force -DiskLayout UEFI 
    # How to send output from imported module to a "_Convert-WIM2VHD.log"
    # Example: powershell -Command "Start-Process 'powershell.exe' -Wait -ArgumentList '-ExecutionPolicy Bypass -Command \"...?
}
catch
{
    Write-Host $Error[0]
    Write-Host $Error[0].Exception.GetType().FullName

What is the best way to get all the output from Convert-WIM2VHD to _Convert-WIM2VHD.log?


Solution

  • How to send output from imported module to a "_Convert-WIM2VHD.log"

    From inside PowerShell:


    From outside PowerShell, when calling the the PowerShell CLI (powershell.exe for Windows PowerShell, pwsh for PowerShell (Core) 7+):


    Character-encoding considerations, i.e. what character encoding is used in the output files:


    [1] Note that this by design merges all streams into the success output stream (which is what makes it possible for Tee-Object to see all output) and therefore "pollutes" the latter; for display output that doesn't matter, however.