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.
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:
# GET the Current Date for our Logfile
# Extract the Date removing the “/”
# Extract the Time removing the “:”
# Build our Filename
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?
C:\PowerShell\newlogfilename-param.ps1 –Preface Bad –Folder C:\BadThings
We now have a simple and adaptable script that can accept parameters. So how does this become a cmdlet?
Join us tomorrow when Sean answers this question and more in Part 3 of Building Your Own PowerShell Cmdlet. Thanks Sean, this is shaping up to be really cool.
I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at email@example.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy