To aid setup and debug scenarios for applications that output data to files, you can live monitor log files with PowerShell.
The Get-Content cmdlet is used to write the contents of a file to the terminal:
PS C:\WINDOWS\system32> Get-Content "C:\Temp\debugtest.txt" Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10
The Get-Content cmdlet has a parameter called -Wait which will keep the file open and write out any lines that are added to the file. It will keep the file open until we either close the terminal or type Ctrl+C to manually terminate execution.
To demonstrate this, lets first create a small script to output lines to a file, which we can then monitor:
For ($i = 1; $i -le 100; $i++) { Add-Content -Path "C:\Temp\debugtest.txt" -Value ('Line {0}' -f $i) Start-Sleep -Seconds 1 }
The above script will write the string “Line ” plus the value of variable $i to a file called C:\Temp\debugtest.txt 100 times, pausing for 1 second after every write.
With the above file creator script running, I’m going to open a new PowerShell terminal and run the following command:
Get-Content "C:\Temp\debugtest.txt" -Wait
This will write out the contents of the file and keep the file open, updating the terminal with the lines being added:
As stated, Get-Command will output the entire contents of the file to the terminal by default. If we are only interested in lines being added since running the command we can use a parameter called -Tail. Tail (or its alias -Last) will output the last x number of lines in the file. You must specify at least 1 or an error will occur:
Get-Content "C:\Temp\debugtest.txt" -Wait -Tail 1