Code Snippets in PowerShell ISE

Granted, PowerShell doesn’t always come with all the features you need right out of the box. However, because we have the power of .NET and an awesome scripting language, we can pretty much do whatever we need to do and we don’t have to wait for the PS team to ship V-Next.

The PowerShell team has taken this philosophy into the development of the ISE as well. In a couple previous posts here and here, I have talked about some very basic customizations using the $PSISE variable that comes with the Scripting Integrated Environment.

One thing I love about PS V2 is Advanced Functions. The only bummer is there is a lot of boilerplate text for each one. This sounds like a perfect opportunity for a code snippet. We can add some functions to our $PROFILE in the PowerShell ISE to make this happen.

First of all, we need to open our $profile script. It probably doesn’t exist so you can do the following. Note that the ISE is a PS host and it has its own profile, different than the one for PowerShell.exe that you use in Console.Exe.

new-item -type file -force $profile

Now we can open it in the ISE with the following line


Now that we have the $profile open, we can create a function that will insert some text into the file that is currently being edited.

function Insert-Text 
    [parameter(Mandatory=$true, ValueFromPipeline=$true]
$currentFilePath = $psise.CurrentOpenedFile.FullPath
$currentFile = $psIse.CurrentOpenedRunspace.OpenedFiles | 
               where {$_.FullPath -eq $currentFilePath}

This function will insert text into the current script at the cursor’s location.

Now we need to write the actual snippet, which can also be a function

function New-FunctionTemplate
$f = @"
function Verb-Noun {
param (
    [parameter(Mandatory=$true, ValueFromPipeline=$true)
begin {}
process {}
end {}
Insert-Text -text $f

The last line uses the Insert-Text function that we just created and inserts the snippet that is stored in the HereString $f.

Now we need to put it together and create a shortcut key and a new custom menu to insert this text.

$psIse.CustomMenu.Submenus.Add("_Function Template", {New-FunctionTemplate}, "Alt+F")

For this particular instance, I chose the name New FunctionTemplate and used Alt F for the keyboard shortcut.


Comments (1) -

business directory 1/13/2015 1:36:29 PM

I discovered your blog site on google and check a few of your early posts. Continue to keep up the very good operate. I just additional up your RSS feed to my MSN News Reader. Seeking forward to reading more from you later on!…

Comments are closed