PowerShell snippet: Show-TextFile

You know those times that you need to show a log file or some text file?

<# 
 .Synopsis
  Open NotePad with the specified filename
 .Description
  Open NotePad with the specified filename
 .Parameter FileName
  Name of text file to open
 .Parameter ScrollToEnd
  Scroll to the bottom of the opened file
 .Parameter Wait
  Wait for Notepad to close before continuing script
 .Parameter Kill 
  Kill Notepad after Timeout -Requires Wait
 .Parameter TimeOut 
  Timeout period in seconds - default = 300 - Requires Wait
 .Example
  Show-TextFile -FileName 'C:\Some path\folder\filename.txt' -ScrollToEnd -Wait -Kill -TimeOut 30 
#>
function Show-TextFile {
    param (
        [string]$FileName,
        [switch]$ScrollToEnd,
        [switch]$Wait,
        [switch]$Kill,
        [int]$TimeOut = 300
    )
    if (Test-Path -Path $FileName) {
        $proc = Start-Process -FilePath 'NotePad.exe' -ArgumentList "$FileName" -NoNewWindow -PassThru
        if ($ScrollToEnd) { 
            # Use VBScript to send Ctrl-End keystroke to Notepad
            $wshell = New-Object -ComObject wscript.shell
            $title = Split-Path -path $FileName -Leaf
            Start-Sleep -seconds 0.5
            $wshell.AppActivate($title) | Out-Null
            $wshell.SendKeys('^{END}') | Out-Null
        }
        if ($Wait) {
            Write-Host "To continue, close Notepad for '$FileName'"
            if (-not (Wait-Process -InputObject $proc -Timeout $TimeOut -ErrorAction SilentlyContinue)) {
                if (-not $Proc.HasExited) {
                    if ($Kill) {
                        Write-Host "Closed Notepad for $FileName"
                        Stop-Process -InputObject $proc -Force
                    } }
            }
        }
    }
    else {
        Write-Warning "Show-TextFile -FileName not found: $FileName"
    }
} # Show-TextFile

Leave a Reply