0

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.

1
  • the function i wrote actually worked. my mistake. I wrote $logWrite "starting script", instead of logWrite "starting script..." Commented Oct 19, 2013 at 6:05

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Beware that Start-Transcript does not capture output from EXEs. More often than not, I want exe output and am willing to give up write-host output.
@KeithHill I agree with your response partially. I believe it also depends on if you want the logging to happen automatically and always or do you want the dependency on the end user to log by invoking the ps1 file everytime using *>.
Wow!, I did not know that I was responding to so much old post.
1

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.

1 Comment

Thank you. I thought i might create my own function, please see snippet code. Let me know your thoughts on this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.