Weekend Scripter: Build Your Own PowerShell Cmdlet: Part 2 of 9

Summary: Microsoft Windows PowerShell MVP, Sean Kearney, continues his series of guest blogs that detail how to build your own cmdlet.

Microsoft Scripting Guy, Ed Wilson, is here. We have a special week in store for you. Guest blogger and Windows PowerShell MVP, Sean Kearney, has written a series about building cmdlets. For more about Sean, see his previous guest blog posts.

Note This is Part 2 of a nine-part series about building your own Windows PowerShell cmdlet. Read the entire series as it unfolds.

Here’s Sean…

To improve on this script, instead of providing static values, we’ll switch them to parameters with defaulting values. In this way, the script will run as we want it to, but it will allow for more flexibility.

This is done by moving the values we want to pass along in a param block. The three values I want to be adjustable are the LogFileName, the Folder, and the Extension. We can assign them default values, however. The beginning of script will now look like this:

PARAM(

[STRING]$Folder="C:\PowerShell",

[STRING]$Preface="Logfile",

[STRING]$Extension=".log"

)

# GET the Current Date for our Logfile

$Today=GET-DATE

# Extract the Date removing the “/”

$Date=$Today.toshortdatestring().Replace(“/”,””)

# Extract the Time removing the “:”

$Time=$Today.tostring(“HH:mm:ss”).Replace(“:”,”“)

# Build our Filename

$Logfilename=$Folder+"\"+$Preface+”-“+$Date+”-“+$Time+$Extension

Test the new parameters

Now we will save this script as newlogfile-param.ps1 in our C:\PowerShell folder. This new script will behave as before if nothing is passed along to it. But we can now do this to generate the log file with a .txt extension if we like:

C:\PowerShell\newlogfilename-param.ps1 –Extension .txt

Or, now you can create the log file in a totally unique folder and a different preface. Yes. I am having a bit of fun here. We’re going to indicate all of our logs that start with “BAD” and store them in a folder called BadThings. Well, where would you put bad things?

That date/time part of the filename can be improved. By sticking with ISO format ("yyyyMMdd-HHmm") (largest unit first, 24 hour clock) the created files will naturally list in chronological order when sorted by name (which is the default in both GUI and command line).