Today's Friday Fun isn't exactly groundbreaking but you might find it useful in your PowerShell script development process. You might even learn a little something about the PowerShell ISE which is really the point of these articles anyway. How many times have you been working on a script or PowerShell tool and know that you'll have to write some section of code but aren't ready to tackle it now? Hopefully you are at least savvy enough to insert a comment reminding you what you need to do. So why not make this simple step as easy as possible in the PowerShell ISE?
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
When I'm writing a script, my hands are already on the keyboard and I want to be able to do things like this without much effort. In this case I want to be able to insert a line of PowerShelll like this:
# ToDo: <task here>
Like I said, hardly exciting and I could probably type it just as fast. Of course the text could be much longer and I also want to be consistent. One solution would be to create a snippet for the ISE.
New-IseSnippet -Title ToDo -Description "Insert a ToDo comment" -Text "# ToDo: "
This will create a snippet that I can bring up with Ctrl+J.
This obviously works and is a great way for inserting a block of canned code. But it takes a few keystrokes to get to the snippet, insert it and then jump the cursor to the right spot so I can insert the ToDo task.
As an alternative, I can use the PowerShell ISE's object model and programmatically insert text into my script. I can run an expression like this:
$psise.CurrentFile.Editor.InsertText("# [$((Get-Date).ToShortDateString())] ToDo: ")
The command will insert a comment in the current file wherever the cursor is currently located that will also include the date as a short string. I thought it might be handy to know when I added the ToDo item. Of course, this is a lot to type everytime and I'm obviously not going to do that. So I added these commands to my PowerShell ISE profile script.
$action = { $psise.CurrentFile.Editor.InsertText("# [$((Get-Date).ToShortDateString())] ToDo: ") #jump cursor to the end $psise.CurrentFile.editor.SetCaretPosition($psise.CurrentFile.Editor.CaretLine,$psise.CurrentFile.Editor.CaretColumn) } #add the action to the Add-Ons menu $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("ToDo",$Action,"Alt+2" ) | Out-Null
The commands will add a item to the Add-Ons menu with a keyboard shortcut of Alt+2.
Now whenever I need to insert a ToDo comment, I can hit Alt+2 which will insert the comment and jump the cursor to the end of the line so I can keep typing.
I find these little time-savers add up and make the entire process a bit more enjoyable. As you might imagine there's really no limit to how you could use these techniques. In fact, if you use this as a model for your own time-saver, I hope you'll share.
Enjoy your weekend!