Writing to a log file using powershell - powershell

I wrote a script in powershell and I would like to have it write all activities and errors to a log file. I am a powershell newbie so I need anyone's input.
I created a function
function logWrite
{
param ([string]$logstring)
add-content $logfile -value $logstring
}
Instead of using Write-host i use the logWrite but I am getting errors:
Unexpected token 'starting script' in expression or statement. at
d:\scripts\tmain.ps1
Appreciate everyone's feedback in advance.

You can also use the Start-Transcript cmdlet in your script, which will copy all of the console input and output (including Write-Host) to a file.

The easiest way is to redirect output at the point you invoke the script e.g.:
C:\PS> .\myscript.ps1 *> myscript.log
The *> will redirect all streams to the log file including output, error, warning, verbose and debug. The only output it won't capture is Write-Host output since that is written directly to the host by definition.

Related

Powershell printing global variable to the log file after transcript is stopped

I am running simple application where I start transcript from one file, continue it using -Append option in another file and then end it.
Everything works fine, it logs everything, the only problem is it puts these two lines also in the log file by itself
PS>$global:?
True
right before the end transcript lines
**********************
Windows PowerShell transcript end
End time: 20210507200412
**********************
Any idea what could be the reason?
Im not familiar with the syntax, but the statement $global:? does indeed evaluate to $true, as to why your code is emitting $global:? i cant say.
Ive just tested the following code under PowerShell 5(Windows/ ISE) and 7(Ubuntu WSL Powershell Core) and i dont get the same output as you so i suspect something in your code is outputting $global:? which results in the 2 lines in question? (it could something in your profile etc not necessarily in the code your looking at)
If you run the below sample do you still see the unexpected lines in the output?
$filename = "./transcript-test.log";
Start-Transcript -Path $filename
Write-Host "This is me writing some stuff to the screen..."
Stop-Transcript
Start-Transcript -Path $filename -Append
Write-Host "Writing more stuff to the console after reopening/appending transcript"
Stop-Transcript
Get-Content $filename
Make sure you do a Stop-Transcript before your script ends.

Writing all outputs from nested applications to specific log file using PowerShell

I have a powershell script, p.ps1, which runs a batch-file, b.bat. The batch file runs an application MyApp.exe. I also have a log file saved in local variable $LogFile.
Is there a way to configure the PowerShell script in a way that all nested applications including MyApp.exe will write to the same log file, without changing b.bat and MyApp.exe?
I've already tried:
Start-Process "cmd.exe" "/c b.bat" -Wait | Add-Content $LogFile
And
Start-Process "cmd.exe" "/c b.bat" -Wait | Out-File $LogFile -Append
Expected Results:
All outputs will be written to $LogFile, I don't care whether outputs will be written to another log file, configured by the code of MyApp.exe.
Actual Results:
All outputs of b.bat were written to $LogFile, but the outputs from MyApp.exe were written to another log file, configured by the code of MyApp.exe.
I think I found the solution:
From the powershell file:
$command = "& 'b.bat' 'arg1' 'arg2'"
Invoke-Expression $command | Add-Content $LogFile
From the myApp code, writing in C#:
Trace.WriteLine(msg);
This way, the c# program wrote everything to the screen. The powershell script caught the output and added it to the log file using Add-Content command.

Powershell pipe all to log

I'm very new to powershell and I'm looking to pipe all lines to an output file for logging with it's time, but I would rather not explicitly pipe all cmdlets to the log file to avoid visual clutter and to make the code easily extensible.
I'm not sure whether existing methods do what I'm asking and I just can't recognize it or what but any pointers or help would be appreciated.
If you want to capture all of the output generated in a PowerShell session (including other streams such as verbose or error messages) you can use Start-Transcript at the start of your script and Stop-Transcript at the end.
If you want to output specific log entries, consider using a Write-Log function as described in one of the answers here: Create Log File in Powershell
Or here's a simple version to get your started:
function Write-Log {
Param(
$Message,
$Path = "$env:USERPROFILE\log.txt"
)
function TS {Get-Date -Format 'hh:mm:ss'}
"[$(TS)]$Message" | Tee-Object -FilePath $Path -Append | Write-Verbose
}
Write-Log 'Some message'
This adds a timestamp to the start of the message and directs it to the Verbose output stream as well as a file via Tee-Object. You can then see the Verbose messages if you enable them via $VerbosePreference (or by supporting -Verbose in your script).
Alternatively, if you want to redirect all output from your script that isn't the other message streams (e.g just things sent to the standard pipeline) you could save the script, run it from within PowerShell and then pipe its output to another command such as Out-File, e.g:
.\yourscript.ps1 | Out-File output.txt

Powershell outputting an executable into a text file

I'm trying to write a Powershell script for work that will take the output of w32tm.exe \monitor and output everything into a text file. I'm trying the following code, however something is wrong since I'm able to create the text file, but nothing is being written in it:
#Take output of w32tm.exe and output into a plain text file
$file = "C:\Documents and Settings\a411882\My Documents\Scripts\timeScript.txt"
$executable = "w32tm.exe /monitor"
invoke-expression $executable | out-file -filepath $file
What am I doing wrong here? I'm new to Powershell so any advice would be greatly appreciated!
EDIT:
I can get all of the data to be displayed on the console when I run this, however I want the data to be written on the text file.
EDIT 2:
I managed to get everything to finally output. I wanted to try avoiding using the > operator to write out to the text file in hopes of learning a little more on the out-file cmdlet however doing a simple invoke-expression $executable > $file managed to get the job done. I still don't understand why the cmdlet wouldn't work properly.
Perhaps Invoke-Expression isn't properly sending output to stdout? I wouldn't expect that, but stranger things have happened. Try running w32tm.exe on its own:
$file = "C:\Documents and Settings\a411882\My Documents\Scripts\timeScript.txt"
w32tm.exe /monitor | Out-File -FilePath $file
You could use Start-Process which allows you to redirect also the error output:
Start-Process w32tm.exe -ArgumentList "/monitor" -Wait -RedirectStandardOutput "output.txt" -RedirectStandardError "error.txt"

In PowerShell how to capture error, warning, write-host output into a single file?

In PowerShell how to capture error, warning, write-host output into a single file?
When I execute the external command/ write-warning/ write-error/ write-host I need all the information to be captured in a file.
when I redirect the write-error to a log file it will not show the same content as it's been displayed on the console. It will have some other information which I don't need.
Is it possible to prefix error with ERROR: , warning with WARN: in the log file?
Have a look at PowerShell 2.0: A Configurable and Flexible Script Logger Module by Oisin. It should be possible to prefix the message with your custom string ('ERROR', 'WARN',...)
The simple way to do this is to use cmd.exe e.g.:
cmd /c powershell.exe -file <path_to_script> > script.log
Perhaps Start-Transcript and Stop-Transcript will do what you want. (PowerShell 2.0)