Author Posts

January 1, 2012 at 12:00 am

by lasty12 at 2013-01-19 12:18:00

Hello all, this is my first post!

I have recently started teaching myself powershell and love it!

My question is this: What syntax do I need to add to create a log file for each script that I create?

Ideally the log file would be in "c:\logs" location for example and a new log would be created each time I run a script – so that I can diagnose failures/successes etc.

Any help gratefully appreciated!

Lasty12

by RichardSiddaway at 2013-01-19 12:39:56

There's a couple of ways that come to mind.

First off use New-EventLog to create an event log & use Write-EventLog to write messages on script start, finish, partial completion etc.

The other way is to create a text file – could make one per day and use Add-Content to write your messages into the file

In either case I would add the name of the script, a timestamp and who is running the script.

Your script will need to have all of the calls to write to the log added as you create it.

A third option is to use write-verbose and have the comments on screen

by lasty12 at 2013-01-19 12:51:13

Thanks Richard.

If possible, please can you give me an example of what syntax I would need to enter for any of the above options?

For example, in a basic command such as "route add 10.0.0.0 mask 255.255.0.0 10.10.12.12 -p" I would like all progress recorded.

by DonJ at 2013-01-19 12:52:27

Lasty, understand that there's no built-in logging mechanism. You can use Out-File to write to a file, but you have to insert those statements in your script. A timstamp, as Richard suggests, is a good way to avoid overwriting old files. You can use Get-Date to get the current date and time, and one of its methods to produce (for example) a filename-friendly date and time.

So there's no way to magically record all progress – you only get what you write to the file yourself.

by lasty12 at 2013-01-19 12:59:50

Thanks DonJ, That makes sense!

I will work on Out-File using date/time stamps and see where that leads me 🙂

by sunnyc7 at 2013-01-23 12:37:36

I wanted to add a quick note:
a) You can use CLFS (Common Log File System) with Powershell, but I havent seen any Powershell code related to that.
There is a C# example here.
b) Another interesting way would be to use Log4Net (I havent used it). Here is an example.
http://www.dovetailsoftware.com/blogs/g ... powershell

hth