Friday, February 08, 2008

PwrShl: Create a log file

I'm trying to teach myself (learn) how to use Power Shell.

I thought I'd start by learning how to do a few simple tasks.
Append to a file
Get the current date and time
Pass arguments to a script/

The above is enough to create a simple log file utility. By which I mean a script which can be called to append text, preceded by a time stamp, a specified file.

Appending to a file is easy, because of 'add-content'.
add-content C:\test.txt "some text"
Getting the current DateTime is done with 'get-date' and is easily turned into a string.
(get-date).tostring()
Strings are concatenated with a plus sign
$dt = (get-date).tostring()
add-content C:\test.txt $dt + "some text"
Arguments are accessed via the $args array. So assuming the text is passed as an argument.
$dt = (get-date).tostring()
add-content C:\test.txt $dt + $args[0]
Put it all into a single line and pass the file name as a single path
add-content $args[0] ((get-date).tostring()) + $args[1]
Save it to C:\AppendToLog.ps1 and then call it.
PS > set-executionpolicy unrestricted
PS > & 'C:\AppendToLog.ps1' 'C:\test.log' 'the text to log'
or
powershell.exe -command "& 'C:\AppendToLog.ps1' 'C:\test.log' 'the text to log'"
Jobs a good'un.

0 comments:

Post a Comment

I get a lot of comment spam :( - moderation may take a while.