Skip to content

Instantly share code, notes, and snippets.

@altrive
Last active June 8, 2019 04:44
Show Gist options
  • Select an option

  • Save altrive/7973332 to your computer and use it in GitHub Desktop.

Select an option

Save altrive/7973332 to your computer and use it in GitHub Desktop.
Utility function to create custom PowerShell ISE code snippets

Register new custom ISE snippets

Sample code to create "PSCredential" ISE code snippet

New-IseCustomSnippet -Title "PSCredential" -Description "Create new PSCredential object" -ScriptBlock {
$cred = New-Object Management.Automation.PsCredential("Administrator", (ConvertTo-SecureString "<#Stub#>" -AsPlainText -Force))
}

Sample code to create "Stopwatch" ISE code snippet

New-IseCustomSnippet -Title "Stopwatch" -Description "Measure PowerShell code block execution times" -ScriptBlock {
$sw = [Diagnostics.Stopwatch]::StartNew()
foreach($i in 1..1000)
{
    #Stub
}
$elapsed = $sw.Elapsed
Write-Host ("Elapsed {0} [ms]" -f $elapsed.TotalMilliseconds)
}

Manage registered snippets

Registered snippets are stored in "snippets" folder at user profile path.

#Get snippets folder path
Join-Path (Split-Path -Parent $profile) "snippets" -Resolve

Using custom ISE snippets

Press Ctrl+J on ISE editer to show registered snippets list. If you don't use ISE default snippets. set following ISE options

$psISE.Options.ShowDefaultSnippets =$false
function New-IseCustomSnippet
{
param (
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory)]
[string] $Title,
[ValidateNotNullOrEmpty()]
[string] $Description = "Description",
[string] $Author = "",
[Parameter(Mandatory)]
[ScriptBlock] $ScriptBlock
)
$stubText = "<#Stub#>"
$text = $ScriptBlock.ToString()
$caretOffset = $text.IndexOf($stubText) #Find Stub text
if ($caretOffset -gt 0){
$text = $text.Remove($caretOffset, $stubText.Length) #Remove Stub text
}
else {
$caretOffset = 0 #Reset caret position
}
$params = @{
Title = $Title
Description = $Description
Author = $Author
Text = $text
CaretOffset = $caretOffset
}
New-IseSnippet @params -Force
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment