Run me!
#Create custom snippets $snippet1 = @{ Title = "New-Snippet"; Description = "Create a New Snippet"; Text = @" `$snippet = @{ Title = `"Put Title Here`"; Description = `"Description Here`"; Text = @`" Code in Here `"@ } New-IseSnippet @snippet "@ } New-IseSnippet @snippet1 –Force #TRY Catch Custom Objects $snippet = @{ Title = "Try/Catch/Custom Objects"; Description = "A great way to get good streamlined output while Try/Catching"; Text = @" try {`$a=Get-WmiObject -Class Win32_ComputerSystem -ErrorAction Stop -ComputerName $name} catch{`$a= [pscustomobject]@{Name=`$name;Domain="Access Denied"}} [pscustomobject]@{RUM_Name=`$name;ReplyName=`$a.Name;Domain=`$a.Domain} "@ } New-IseSnippet @snippet #PS Custom Object $snippet = @{ Title = "Custom Object"; Description = "I always forget how to do this!"; Text = @" [pscustomobject]@{Column1='PutCodeToCalculateMeHere';Column2="Put code here"} "@ } New-IseSnippet @snippet #Sample Progress bar $snippet = @{ Title = "Write Progress Sample"; Description = "Progress and how to do it"; Text = @" #sample range of numbers `$users = (1..13000) #setting up base number `$i=0 ForEach (`$user in `$users){ #increment `$i++ #Round the numbers up for a nice output and then Write-Progress Write-Progress -Activity "Processing `$user" -PercentComplete ((`$i/`$users.Count) * 100) -Status ("`$i out of " + `$users.Count +" completed "+[math]::Round(((`$i/`$users.Count) * 100),2) +" %") } "@ } New-IseSnippet @snippet #Old Fashioned Custom Objects $snippet = @{ Title = "PS 2.0 Custom Objects"; Description = "Old Fashioned Custom Objects"; Text = @" `$ObjectProperties = @{ Name = `$user RecipientType=`$mbx.RecipientType LastLoggedOnUserAccount=`$mbxstat.LastLoggedOnUserAccount LastLogOffTime=`$mbxstat.LastLogOffTime LastLogonTime=`$mbxstat.LastLogonTime } `$obj = New-Object PSObject -Property `$ObjectProperties "@ } New-IseSnippet @snippet #Old School try/catch custom Object $snippet = @{ Title = "Old School try/catch custom object "; Description = "Using try/catch to create custom objects is a great way to capture information succinctly. However, the [PSCustomObject] Accelerator/casting only work on PS 3 and up. This example uses old school Items to get around that"; Text = @" `$users | ForEach-Object { `$name = `$_ try {`$a=Get-mailbox `$name -erroraction Stop} catch{ `$ObjectProperties = @{ Name = `$name HiddenFromAddressListsEnabled="MBX Not Found" } `$a = New-Object PSObject -Property `$ObjectProperties} `$ObjectProperties = @{ Name = `$name HiddenFromAddressListsEnabled=`$a.HiddenFromAddressListsEnabled } New-Object PSObject -Property `$ObjectProperties } "@ } New-IseSnippet @snippet #Popup message $snippet = @{ Title = "Popup Message"; Description = "Add a simple pop-up message"; Text = @" `$msg = New-Object -ComObject WScript.Shell `$msg.Popup("Hi Chris", 5, "DeadMau5", 48) "@ } New-IseSnippet @snippet #Wait for file to change $snippet = @{ Title = "Wait For File to Change"; Description = "Wait for File to change While Example"; Text = @" `$Initial_LastWriteTime = get-item .\upload.txt | Select -ExpandProperty LastWriteTime #Will Only exit the loop if the file changes While(`$Initial_LastWriteTime -eq ( get-item .\upload.txt | Select -ExpandProperty LastWriteTime)){"Waiting for the file to change...";start-sleep 5} "File changed!" #DO STUFF HERE "@ } New-IseSnippet @snippet #Calculated Properties $snippet = @{ Title = "Calculated Properties"; Description = "Use to make custom selections "; Text = @' Select-Object @{Name=‘ComputerName‘;Expression={$_.ComputerName}},` @{Name=‘User’;Expression={$_.UserName}},` '@ } New-IseSnippet @snippet #install the XAML based GUI snippet $snippet = @{ Title = "Make a GUI with XAML and WPF"; Description = "Create your GUI in minutes in Visual Studio then paste it here"; Text = @' #ERASE ALL THIS AND PUT XAML BELOW between the @" "@ $inputXML = @" <Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication2" mc:Ignorable="d" Title="FoxDeploy Awesome Tool" Height="416.794" Width="598.474" Topmost="True"> <Grid Margin="0,0,45,0"> </Grid> </Window> "@ $inputXML = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N' -replace '^<Win.*', '<Window' [void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework') [xml]$XAML = $inputXML #Read XAML $reader=(New-Object System.Xml.XmlNodeReader $xaml) try{$Form=[Windows.Markup.XamlReader]::Load( $reader )} catch{Write-Warning "Unable to parse XML, with error: $($Error[0])`n Ensure that there are NO SelectionChanged properties (PowerShell cannot process them)" throw} #=========================================================================== # Load XAML Objects In PowerShell #=========================================================================== $xaml.SelectNodes("//*[@Name]") | %{"trying item $($_.Name)"; try {Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name) -ErrorAction Stop} catch{throw} } Function Get-FormVariables{ if ($global:ReadmeDisplay -ne $true){Write-host "If you need to reference this display again, run Get-FormVariables" -ForegroundColor Yellow;$global:ReadmeDisplay=$true} write-host "Found the following interactable elements from our form" -ForegroundColor Cyan get-variable WPF* } Get-FormVariables #=========================================================================== # Use this space to add code to the various form elements in your GUI #=========================================================================== #Reference #Adding items to a dropdown/combo box #$vmpicklistView.items.Add([pscustomobject]@{'VMName'=($_).Name;Status=$_.Status;Other="Yes"}) #Setting the text of a text box to the current PC name #$WPFtextBox.Text = $env:COMPUTERNAME #Adding code to a button, so that when clicked, it pings a system # $WPFbutton.Add_Click({ Test-connection -count 1 -ComputerName $WPFtextBox.Text # }) #=========================================================================== # Shows the form #=========================================================================== write-host "To show the form, run the following" -ForegroundColor Cyan '$Form.ShowDialog() | out-null' '@ } New-IseSnippet @snippet
One of the best features of the PowerShell ISE is the presence of Snippets, a great engine to fill in code-snippets for common tasks. I pretty much use this every single day!

Making a new Snippet is kind of difficult though. I found this wonderful little snippet that allows you to easily create more snippets. I know. Snippets in Snippets? Not sure if it is more Ludacris or Inception though…
Rob the PowerShell DBA had this awesome snippet on his blog.
$snippet1 = @{ Title = "New-Snippet"; Description = "Create a New Snippet"; Text = @" `$snippet = @{ Title = `"Put Title Here`"; Description = `"Description Here`"; Text = @`" Code in Here `"@ } New-IseSnippet @snippet "@ } New-IseSnippet @snippet1 –Force
From <http://sqldbawithabeard.com/2014/09/09/powershell-snippets-a-great-learning-tool/>
What does it do? Well, after running this in the ISE, you can hit Control+J and bam, an easy to fill in form to create a nice new Snippet.

Fill in the values and hit F5 to create the snippet.
I love this so much, here are a bunch of snippets I use everywhere.
Custom Objects using Try/Catch
I made a whole blog post about doing this. It’s now my go-to standard when making information gathering tools.
$snippet = @{ Title = "Try/Catch/Custom Objects"; Description = "A great way to get good streamlined output while Try/Catching"; Text = @" try {`$a=Get-WmiObject -Class Win32_ComputerSystem -ErrorAction Stop -ComputerName $name} catch{`$a= [pscustomobject]@{Name=`$name;Domain="Access Denied"}} [pscustomobject]@{RUM_Name=`$name;ReplyName=`$a.Name;Domain=`$a.Domain} "@ } New-IseSnippet @snippet
Quick PS Custom Object
Sometimes you just need to grab a bunch of info about a thing and make it a single object. Here’s how:
$snippet = @{ Title = "Custom Object"; Description = "I always forget how to do this!"; Text = @" #Add more columns to the object by adding extra key/values [pscustomobject]@{Name=$name;Domain="Access Denied"} "@ } New-IseSnippet @snippet
Progress Bar within ForEach Loop
This looks easy but I would forget how to do it constantly.
$snippet = @{ Title = "Write Progress Sample"; Description = "Progress and how to do it"; Text = @" #sample range of numbers `$users = (1..13000) #setting up base number `$i=0 ForEach (`$user in `$users){ #increment `$i++ #Round the numbers up for a nice output and then Write-Progress Write-Progress -Activity "Processing `$user" -PercentComplete ((`$i/`$users.Count) * 100) -Status ("`$i out of " + `$users.Count +" completed "+[math]::Round(((`$i/`$users.Count) * 100),2) +" %") } "@ } New-IseSnippet @snippet
PowerShell V1 Custom Object Format
Sometimes you have to work on ancient systems and forget how to make old-school custom objects. Never again! This example is based on capturing the output of Get-MailboxStatistics within $mbx.
$snippet = @{ Title = "PS 2.0 Custom Objects"; Description = "Old Fashioned Custom Objects"; Text = @" `$ObjectProperties = @{ Name = `$user RecipientType=`$mbx.RecipientType LastLoggedOnUserAccount=`$mbxstat.LastLoggedOnUserAccount LastLogOffTime=`$mbxstat.LastLogOffTime LastLogonTime=`$mbxstat.LastLogonTime } `$obj = New-Object PSObject -Property `$ObjectProperties "@ } New-IseSnippet @snippet
Old-School Custom Objects using Try/Catch
A repeat of my first Custom Object loop, this time with Pre-V2 objects
$snippet = @{ Title = "Old School try/catch custom object "; Description = "Using try/catch to create custom objects is a great way to capture information succinctly. However, the [PSCustomObject] Accelerator/casting only work on PS 3 and up. This example uses old school Items to get around that"; Text = @" `$users | ForEach-Object { `$name = `$_ try {`$a=Get-mailbox `$name -erroraction Stop} catch{ `$ObjectProperties = @{ Name = `$name HiddenFromAddressListsEnabled="MBX Not Found" } `$a = New-Object PSObject -Property `$ObjectProperties} `$ObjectProperties = @{ Name = `$name HiddenFromAddressListsEnabled=`$a.HiddenFromAddressListsEnabled } New-Object PSObject -Property `$ObjectProperties } "@ } New-IseSnippet @snippet
Display a Popup Prompt
This is a shorty, but a useful one!
$snippet = @{ Title = "Popup Message"; Description = "Add a simple pop-up message"; Text = @" `$msg = New-Object -ComObject WScript.Shell `$msg.Popup("Hi Chris", 5, "DeadMau5", 48) "@ } New-IseSnippet @snippet
Sample REST Method using Push
$snippet = @{ Title = "Sample REST Method Request"; Description = "Use this sample to perform a Post Method using Invoke-RestMethod"; Text = @" if (`$Type -eq 'Address'){ {Write-Verbose "Sending an Address"<#SendaMessagestuff#> `$body = @{ type = "address" title = `$Placename address = `$PlaceAddress } } `$Sendattempt = Invoke-RestMethod -Uri `$PushURL -Credential `$cred -Method Post -Body `$body -ErrorAction SilentlyContinue If (`$Sendattempt.StatusCode -eq "200"){Write-Verbose "OK"} else {Write-Warning "error encountered, check ``$attempt for more info" `$global:Sendattempt = `$Sendattempt } } "@ } New-IseSnippet @snippet
Using WPF in PowerShell
If you want to create forms in Visual Studio, use this snippet. Simply copy and paste from Visual Studio.
$snippet = @{ Title = "Make a GUI with XAML and WPF"; Description = "Create your GUI in minutes in Visual Studio then paste it here"; Text = @' #ERASE ALL THIS AND PUT XAML BELOW between the @" "@ $inputXML = @" <Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication2" mc:Ignorable="d" Title="FoxDeploy Awesome Tool" Height="416.794" Width="598.474" Topmost="True"> <Grid Margin="0,0,45,0"> </Grid> </Window> "@ $inputXML = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N' -replace '^<Win.*', '<Window' [void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework') [xml]$XAML = $inputXML #Read XAML $reader=(New-Object System.Xml.XmlNodeReader $xaml) try{$Form=[Windows.Markup.XamlReader]::Load( $reader )} catch [System.Management.Automation.MethodInvocationException] { Write-Warning "We ran into a problem with the XAML code. Check the syntax for this control..." write-host $error[0].Exception.Message -ForegroundColor Red if ($error[0].Exception.Message -like "*button*"){ write-warning "Ensure your <button in the `$inputXML does NOT have a Click=ButtonClick property. PS can't handle this`n`n`n`n"} } catch{#if it broke some other way 😀 Write-Host "Unable to load Windows.Markup.XamlReader. Double-check syntax and ensure .net is installed." } #=========================================================================== # Store Form Objects In PowerShell #=========================================================================== $xaml.SelectNodes("//*[@Name]") | %{Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name)} Function Get-FormVariables{ if ($global:ReadmeDisplay -ne $true){Write-host "If you need to reference this display again, run Get-FormVariables" -ForegroundColor Yellow;$global:ReadmeDisplay=$true} write-host "Found the following interactable elements from our form" -ForegroundColor Cyan get-variable WPF* } Get-FormVariables #=========================================================================== # Actually make the objects work #=========================================================================== #Reference Sample entry of how to add data to a field #$vmpicklistView.items.Add([pscustomobject]@{'VMName'=($_).Name;Status=$_.Status;Other="Yes"}) #$WPFtextBox.Text = $env:COMPUTERNAME #$WPFbutton.Add_Click({$WPFlistView.Items.Clear();start-sleep -Milliseconds 840;Get-DiskInfo -computername $WPFtextBox.Text | % {$WPFlistView.AddChild($_)} }) #=========================================================================== # Shows the form #=========================================================================== write-host "To show the form, run the following" -ForegroundColor Cyan '$Form.ShowDialog() | out-null' '@ } New-IseSnippet @snippet
Hi Stephen, thanks for your work done here.
It is really useful.
Everyone start programming in powershell should see your blog.
LikeLike