Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Thursday, February 20, 2014

Adding Some Code Templates to the PowerShell ISE

Today I’m sitting at the car dealership waiting on my wife’s car to get a recall fixed.  Luckily I can carry my entire office on my laptop (I’ve been here for 3 hours).  I’m working on finalizing my code for the 2014 PowerShell Summit in April so of course I keep finding better and better ways of writing my own code.  (BTW, my session at the summit is on Tuesday)  What I am focused on is to take my HelpDesk module code to the next level, but also to be able to do it quickly and easily.  This has finally given me a reason to use the Snippets functionality in the PowerShell ISE.

I wrote up some code that will help me a lot and saved it as a PowerShell script called HDSnippet.ps1.  This code will be my template.

Now, before we begin, you need to be on PowerShell V3.  I know that a lot of you who are going to be taking my PowerShell classes over then next few months are still in a V2 environment.  That is OK.  Copy and Paste still work.  For those of you on PowerShell V3, open the ISE and press Ctrl-J.  We are going to be adding to this list.

I’m going to do this as a User-Defined snippet. My default folder for my snippets is C:\Users\JASON\Documents\WindowsPowerShell\Snippets.  Since the Snippets folder does not yet exist, you will want to create it.  This is also where the cmdlet New-IseSnippet will automatically place your new snippet file.

I’m now going to create a little script to help reduce my typing.

$Text = (Get-Content -Raw -Path "C:\Users\JASON\Documents\WIndowsPowerShell\Snippets\HDSnippet.ps1")

 

$Props = @{

    "Title" = "NewHDCmdlet";

    "Description" = "Default code for a new HD module cmdlet";

    "Author" = "Jason A. Yoder"

    "Text" = $Text

 

}

 

New-IseSnippet @Props

 

Since my Snippet is actually code, I have to use the –Raw switch with the Get-Content cmdlet so the Text property of New-IseSnippet processes it correctly.

This will create a new file in the Snippets folder called NewHDCmdlet.snippets.ps1xml.  If you press Ctrl-J now, you will have access to your snippet.  If you decided that you no longer need one of your templates, just delete it from the Snippets folder.

If you want to stop displaying the default snippets and see just yours, in the ISE click Tools –> Options.  Click the General Settings tab and uncheck the Use default snippets.

image

No comments: