INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Customizing PowerShell

Using Snippets in PowerShell_ISE by markdmac
Posted: 4 Mar 15 (Edited 5 Mar 15)

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 Snippet manager 3.

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.

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

<?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> 

CODE --> File-Browser.snippets.ps1xml

<?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>
 

CODE --> Get-DesktopPath.snippets.ps1xml

<?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>
 

CODE --> Get-ScriptPath.snippets.ps1xml

<?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>
 

CODE --> Ping-Check.snippets.ps1xml

<?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>
 

CODE --> PowerShell-OKCancel.snippets.ps1xml

<?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>
 

CODE --> PowerShell-PopUp.snippets.ps1xml

<?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>
 

CODE --> Remove-ComputerFromAD.snippets.ps1xml

<?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>
 

CODE --> Run-Elevated.snippets.ps1xml

<?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>
 

CODE --> Property.snippets.ps1xml

<?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>
 

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 --> 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 

More snippets will be posted as I develop them, so check back here every once in a while.

Back to PowerShell (Microsoft) FAQ Index
Back to PowerShell (Microsoft) Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close