PowerShell Script Logging: Complete Implementation from Screen Output to File Storage

Nov 17, 2025 · Programming · 14 views · 7.8

Keywords: PowerShell | Logging | Add-Content | Custom Function | File Operations

Abstract: This article provides a comprehensive exploration of various methods for implementing logging functionality in PowerShell, with a focus on custom log solutions based on the Add-Content function. Through refactoring the original code, it demonstrates how to redirect screen output to log files named after computer names, and delves into advanced features such as timestamp addition and log level classification. The article also compares the pros and cons of Start-Transcript versus custom functions, offering complete guidance for logging implementations in different scenarios.

Fundamental Concepts of PowerShell Logging

In automated script development, logging is a critical component for ensuring traceability and troubleshooting. The original code uses the Write-Host command to output information to the console, which is useful in interactive scenarios but lacks persistence in automated deployments and long-term monitoring. Redirecting output to the file system addresses this issue, ensuring that operation records are preserved.

Analysis of Core Implementation Solution

Based on the best answer implementation, we first define the log file path and write function:

$Logfile = "D:\Apps\Logs\$(gc env:computername).log"

Function LogWrite
{
   Param ([string]$logstring)
   Add-content $Logfile -value $logstring
}

Key technical points here include:

Code Refactoring and Optimization

The original code requires the following modifications to implement logging:

# Get TCPIP.sys version information
$tcpipVersion = "$(((get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductMajorPart).tostring()).$(((get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductMinorPart).tostring()).$(((get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductBuildPart).tostring()).$(((get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductPrivatePart).tostring())"

LogWrite "TCPIP.sys Version on $computer is: $tcpipVersion"

# Check REMINST share status
if (get-wmiobject win32_share | where-object {$_.Name -eq "REMINST"}) {
    LogWrite "The REMINST share exists on $computer"
} else {
    LogWrite "The REMINST share DOES NOT exist on $computer - Please create as per standards"
}

This refactoring not only implements logging functionality but also improves code readability and maintainability.

Advanced Logging Feature Extensions

Referencing other answers, we can add more practical features to the logging system:

Function Write-Log {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$False)]
        [ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG")]
        [String]$Level = "INFO",
        
        [Parameter(Mandatory=$True)]
        [string]$Message,
        
        [Parameter(Mandatory=$False)]
        [string]$logfile
    )

    $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
    $Line = "$Stamp $Level $Message"
    
    If($logfile) {
        Add-Content $logfile -Value $Line
    }
    Else {
        Write-Output $Line
    }
}

This enhanced version provides:

Alternative Solution Comparison

Start-Transcript Method:

Start-Transcript -Path "Computer.log" -Append
# Execute script code
Stop-Transcript

This method is simple and quick but records all console activities, including error messages and debug output, which may contain excessive irrelevant information.

Custom Function vs Start-Transcript Comparison:

<table> <tr><th>Feature</th><th>Custom Function</th><th>Start-Transcript</th></tr> <tr><td>Precise Control</td><td>High - Only records specified content</td><td>Low - Records all console output</td></tr> <tr><td>Flexibility</td><td>High - Customizable format and logic</td><td>Low - Fixed format</td></tr> <tr><td>Implementation Complexity</td><td>Medium - Requires function writing</td><td>Low - Direct use of built-in commands</td></tr> <tr><td>Suitable Scenarios</td><td>Production environment, precise logging</td><td>Development debugging, rapid prototyping</td></tr>

Best Practice Recommendations

Based on practical application experience, we recommend:

  1. Path Validation: Check if the target directory exists before writing logs
  2. Error Handling: Add appropriate exception handling mechanisms for file operations
  3. Log Rotation: For long-running scripts, implement log file size limits and rotation strategies
  4. Performance Considerations: High-frequency log writing may impact script performance; consider batch writing or asynchronous processing

Practical Application Scenarios

In enterprise environments, this logging mechanism can be applied to:

Through proper logging, administrators can accurately understand script execution status, quickly locate issues, and improve system maintenance efficiency.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.