Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Snippets in PowerShell_ISE

Customizing PowerShell

Using Snippets in PowerShell_ISE

by  markdmac  Posted    (Edited  )
With the introduction of PowerShell version 3.0, the PowerShell_ISE has gained the ability to use Snippets, little bits of code to help you quickly write scripts.

Please don't forget to rate this FAQ. I strive for ratings of 10, please contact me if you find any problems or have suggestions to make the FAQ better. Thank you.

I've been adding to my list of the default snippets and thought others might like to copy some of my content. First, you should make sure that you have created a PowerShell profile. To do that Open PowerShell and execute New-Item –Path $Profile –Type File –Force.

Note that in the above command I specified -Force which will create a new profile even if you already had one. If you don't want to start clean don't use -Force.

OK, you will now find you have a folder called WindowsPowerShell inside your Documents folder. Inside that there should be a snippets folder. If not you can create it. Snippets are nothing more than XML based text files that contain bits and pieces of code. Regretfully the ISE does a lousy job of letting you manage these files. You can download a nice little bit of code to help you write and manage your own snippets called [link https://bytecookie.wordpress.com/snippet-manager/]Snippet manager 3[/link].

Here is a current list of the snippets I have setup for myself. I'll periodically add more to this list as my own collection grows.

[ul]
[li]Date-Diff: compares dates[/li]
[li]File-Browser: Calls open a file dialog box to select a file[/li]
[li]Get-DesktopPath: Returns the full path to the user's desktop[/li]
[li]Get-Scriptpath: Reports back the directory that the script exists in[/li]
[li]Ping-Check: Tests connectivity to a remote system before taking action[/li]
[li]PowerShell-OKCancel: Provides the user with a pop up with buttons to continue or cancel operation[/li]
[li]PowerShell-PopUp: Provides the user with a pop up with a simple OK button[/li]
[li]Remove-ComputerFromAD: Provides code to remove a computer object from Active Directory[/li]
[li]Run-Elevated: Relaunches a script as admin if it is not already running elevated[/li]
[li]CalculatedProperty: Provides syntax for a calculated property[/li]
[li]Snippet-Maker: A snippet to make snippets![/li]
[/ul]

Use notepad to create text files for each of these snippets and put them in your snippet folder. The file name needs to be like "Date-Diff.snippets.ps1xml". Then from within the PowerShell_ISE use Ctrl+J to access the snippet menu.

[code Date-Diff.snippets.ps1xml]
[pre]<?xml version="1.0" encoding="utf-8"?>
<Snippets xmlns="http://schemas.microsoft.com/PowerShell/Snippets">
<Snippet Version="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>Date-Diff</Title>
<Description>Finds date difference betwwen two dates.</Description>
<Author>Mark D. MacLachlan</Author>
</Header>
<Code>
<Script Language="powershell" CaretOffset="284"><![CDATA[ #Create our log to record start/stop times
$StartDate = Get-Date
$StartDate
Start-Sleep -s 25
$EndDate = Get-Date
$EndDate
$Message = "Ending export at $EndDate"

$TimeExport = NEW-TIMESPAN –Start $StartDate –End $EndDate
$TimeSpent = "Time Spent on Export $TimeExport"
$TimeSpent ]]></Script>
</Code>
</Snippet>
</Snippets>[/pre]
[/code]

[code File-Browser.snippets.ps1xml]
[pre]
<?xml version="1.0" encoding="utf-8"?>
<Snippets xmlns="http://schemas.microsoft.com/PowerShell/Snippets">
<Snippet Version="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>File-Browser</Title>
<Description>Allows user to browse to a file and select it.</Description>
<Author>Mark D. MacLachlan</Author>
</Header>
<Code>
<Script Language="powershell" CaretOffset="448"><![CDATA[ Function Get-FileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
Out-Null

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "All files (*.*)| *.*"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
} #end function Get-FileName

$File = Get-FileName -initialDirectory "c:\"
]]></Script>
</Code>
</Snippet>
</Snippets>
[/pre]
[/code]

[code Get-DesktopPath.snippets.ps1xml]
[pre]
<?xml version="1.0" encoding="utf-8"?>
<Snippets xmlns="http://schemas.microsoft.com/PowerShell/Snippets">
<Snippet Version="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>Get-DesktopPath</Title>
<Description>Gets the path to the user profile desktop location.</Description>
<Author>Mark D. MacLachlan</Author>
</Header>
<Code>
<Script Language="powershell" CaretOffset="56"><![CDATA[ $Desktop = $([environment]::GetFolderPath('Desktop')) ]]></Script>
</Code>
</Snippet>
</Snippets>
[/pre]
[/code]
[code Get-ScriptPath.snippets.ps1xml]
[pre]
<?xml version="1.0" encoding="utf-8"?>
<Snippets xmlns="http://schemas.microsoft.com/PowerShell/Snippets">
<Snippet Version="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>Get-ScriptPath</Title>
<Description>Gets the current script file location</Description>
<Author>Mark D. MacLachlan</Author>
</Header>
<Code>
<Script Language="powershell" CaretOffset="78"><![CDATA[ $PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition ]]></Script>
</Code>
</Snippet>
</Snippets>
[/pre]
[/code]

[code Ping-Check.snippets.ps1xml]
[pre]
<?xml version="1.0" encoding="utf-8"?>
<Snippets xmlns="http://schemas.microsoft.com/PowerShell/Snippets">
<Snippet Version="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>Ping-Check</Title>
<Description>Checks if a server is online.</Description>
<Author>Mark D. MacLachlan</Author>
</Header>
<Code>
<Script Language="powershell" CaretOffset="244"><![CDATA[ $Computer = $env:COMPUTERNAME
if(!(Test-Connection -Cn $Computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{
$Report = "$Computer is offline or unreachable"
}
Else{
$Report = "$Computer is online"
} ]]></Script>
</Code>
</Snippet>
</Snippets>
[/pre]
[/code]

[code PowerShell-OKCancel.snippets.ps1xml]
[pre]
<?xml version="1.0" encoding="utf-8"?>
<Snippets xmlns="http://schemas.microsoft.com/PowerShell/Snippets">
<Snippet Version="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>PowerShell-OKCancel</Title>
<Description>Displays a windows popup with OK cancel buttons and cancels if selected</Description>
<Author>Mark D. MacLachlan</Author>
</Header>
<Code>
<Script Language="powershell" CaretOffset="292"><![CDATA[#0:
#1:Cancel
#2:Retry Ignore
#3:No Cancel
#4:No
#5:Cancel

$TextMsg = "Do you wish to continue?"
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Output = [System.Windows.Forms.MessageBox]::Show("$TextMsg","Confirm Action",1)
if ($Output -eq "CANCEL")
{Exit}]]></Script>
</Code>
</Snippet>
</Snippets>
[/pre]
[/code]

[code PowerShell-PopUp.snippets.ps1xml]
[pre]
<?xml version="1.0" encoding="utf-8"?>
<Snippets xmlns="http://schemas.microsoft.com/PowerShell/Snippets">
<Snippet Version="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>PowerShell-PopUp</Title>
<Description>Creates a .Net Pop-up message</Description>
<Author>Mark D. MacLachlan</Author>
</Header>
<Code>
<Script Language="powershell" CaretOffset="133"><![CDATA[ [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.MessageBox]::Show("Hello, World.") ]]></Script>
</Code>
</Snippet>
</Snippets>
[/pre]
[/code]

[code Remove-ComputerFromAD.snippets.ps1xml]
[pre]
<?xml version="1.0" encoding="utf-8"?>
<Snippets xmlns="http://schemas.microsoft.com/PowerShell/Snippets">
<Snippet Version="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>RemoveComputerFromAD</Title>
<Description>Removes a computer account from Active Directory</Description>
<Author>Mark D. MacLachlan</Author>
</Header>
<Code>
<Script Language="powershell" CaretOffset="404"><![CDATA[$Server = "COMPUTERNAME"
$searcher = [adsisearcher][adsi]""
$searcher.filter ="(cn=$Server)"
#Search Active Directory for the current location of the computer object
$searchparm = $searcher.FindOne()
#Assign $deleteoldcomp to the found path
$deleteoldcomp = $searchparm.path
#Assign the ADSI object to a variable
$delcomp = [adsi]("$deleteoldcomp")
try {$delcomp.deletetree()}catch{}
$delcomp.setinfo() ]]></Script>
</Code>
</Snippet>
</Snippets>
[/pre]
[/code]

[code Run-Elevated.snippets.ps1xml]
[pre]
<?xml version="1.0" encoding="utf-8"?>
<Snippets xmlns="http://schemas.microsoft.com/PowerShell/Snippets">
<Snippet Version="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>Run-Elevated</Title>
<Description>Forces a script to run in elevated mode.</Description>
<Author>Mark D. MacLachlan</Author>
</Header>
<Code>
<Script Language="powershell" CaretOffset="1351"><![CDATA[ # Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)

# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator

# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running "as Administrator" - so change the title and background color to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$Host.UI.RawUI.BackgroundColor = "DarkBlue"
clear-host
}
else
{
# We are not running "as Administrator" - so relaunch as administrator

# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";

# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;

# Indicate that the process should be elevated
$newProcess.Verb = "runas";

# Start the new process
[System.Diagnostics.Process]::Start($newProcess);

# Exit from the current, unelevated, process
exit
}

# Run your code that needs to be elevated here ]]></Script>
</Code>
</Snippet>
</Snippets>
[/pre]
[/code]

[code Calculated Property.snippets.ps1xml]
[pre]
<?xml version='1.0' encoding='utf-8' ?>
<Snippets xmlns='http://schemas.microsoft.com/PowerShell/Snippets'>
<Snippet Version='1.0.0'>
<Header>
<Title>Calculated Property</Title>
<Description>Syntax for a Calculated Property</Description>
<Author></Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>

<Code>
<Script Language='PowerShell' CaretOffset='5'>
<![CDATA[@{N='Title';E={ }}]]>
</Script>
</Code>

</Snippet>
</Snippets>
[/pre]
[/code]

I learned a new trick today. Rather than relying on the SnippetManager you can use PowerShell_ISE to create new snippets. One I learned that I decided it would be fun to risk creating holes in the space/time continuum by making a snippet that can make snippets.

Run the following code inside your PowerShell_ISE. It will create a Snippet-Maker snippet for you. Please take note that after calling up this snippet, you will need to uncomment the line that has '@ in it.

[code PowerShell: Snippet-Maker]
$Snippet = @'
$Snippet = @'
#This is a snippet to make new snippets
#Put your code here
#Edit the title and description below
#'@ #Uncomment the start of this line
#Then run the script with the following line:
New-IseSnippet -Title "Snippet-Maker" -Description "Syntax creating a snippet from any PowerShell Code" -Text $Snippet
'@
New-IseSnippet -Title "Snippet-Maker" -Description "Syntax creating a snippet from any PowerShell Code" -Text $Snippet
[/code]

More snippets will be posted as I develop them, so check back here every once in a while.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top