Posts mit dem Label PowerShell werden angezeigt. Alle Posts anzeigen
Posts mit dem Label PowerShell werden angezeigt. Alle Posts anzeigen

Samstag, 20. November 2010

Eval-Selection in ISE editor, result in editor pane

Here is a little demo showing, who to use ISEs editor pane to display untruncated, unwrapped results.

Run the script in ISE.
Open a new editor.
Tpye dir and press F7:



            
            
function Eval-Selection            
{            
    # Bernd Kriszio 2010-11-21            
    # http://pauerschell.blogspot.com/            
    # twitter @bernd_k            
                
                    
    $editor = $psise.CurrentFile.Editor            
            
    if ($editor.SelectedText)            
    {            
        $inputScript = $editor.SelectedText            
        $editor.InsertText('')            
        $editor.InsertText($inputScript)            
        $result = Invoke-expression $inputScript | out-String            
        $editor.insertText("`r`n")            
        $editor.InsertText($result)            
            
    }            
    else            
    {            
        $inputScript = $editor.Text            
        $EndLine =  $editor.LineCount             
        $EndColumn = $editor.GetLineLength($EndLine) + 1            
        $editor.SetCaretPosition($EndLine, $EndColumn)            
        $result = Invoke-expression $inputScript | out-String            
        $editor.insertText("`r`n")            
        $editor.InsertText($result)            
    }            
}                    
                    
             
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Eval-Selection", {Eval-Selection} ,  'f7')

Edited
After playing a while, I modified the rules for the case, when nothing is selected. Now I use just the single line, the caret is in. Further I added the -width 1000 parameter to make it realy an improvement about usual output-pane results.

And I have a lot of crazy ideas, what to do if the caret is in an empty line. I don't implement them. Next month I wouldn't remember them myself.

Keep things simple

Bernd

This is the version, I added to my profile:

function Eval-Selection            
{            
    # Bernd Kriszio 2010-11-21            
    # http://pauerschell.blogspot.com/            
    # twitter @bernd_k            
                
                    
    $editor = $psise.CurrentFile.Editor            
                
    # if nothing is selected just use the line the caret is in            
    if (!$editor.SelectedText)            
    {            
        $caretLine = $editor.CaretLine            
        $caretLineEnd = $editor.GetLineLength($caretLine) + 1                
                    
        $editor.Select($caretLine, 1, $caretLine, $caretLineEnd)            
    }            
            
    # if something is selected use it.            
    if ($editor.SelectedText)            
    {            
        $inputScript = $editor.SelectedText            
        $editor.InsertText('')            
        $editor.InsertText($inputScript)            
        $result = Invoke-expression $inputScript | out-String -width 1000            
        if ($editor.CaretColumn -ne 1)            
        {            
            $editor.insertText("`r`n")            
        }            
        $editor.InsertText($result)            
            
    }            
}            

Dienstag, 16. November 2010

Determine Start and End of a Selection in PowerShell Ise

Hello, I' m just working on a new inline outpout mode for SQLPSX a very ambious project to access SQL databases based on PowerShell.

There ISEs Output pane doesn't always satisfy my needs, because it truncates and wraps output but you can put your Output into the current or new Editor panes and that works fine. Today I focus on using the current editor pane. 

My goal is to insert the output exactly at the starting of the line below the selection if there is one or at the end of the editor.

First I found it difficult to get the start and end of a selection, but than I found a clever work around. I can even determine, if a selection was done from left to right or from right to left.

But don't use this possibility. It would be really confusing.

Here is my test code, with which I designed (honestly redesigned) the logic to evaluate the output location in SQLPSX (next release).

Have fun studying it. Just put the code below it into an ISE editor, select some text (or nothing) and press F5.

Bernd


function Get-InfoAboutCurentFilesEditor            
{            
    $editor          = $psIse.CurrentFile.Editor            
    $LineCount       = $editor.LineCount            
    $CaretLine       = $editor.CaretLine            
    $caretColumn     = $editor.CaretColumn            
    $CaretLineLength = $editor.GetLineLength($CaretLine)            
    $CaretAtLineEnd  = $caretColumn -eq $CaretLineLength + 1            
    $CaretInLastLine = $CaretLine -eq $LineCount            
    $SelectedText    = $editor.SelectedText            
    $hasSelection    = $SelectedText -ne ''            
                
    if ($hasSelection)            
    {            
        # delete selected text            
        $editor.InsertText('')            
        $StartLine =  $editor.CaretLine            
        $StartColumn = $editor.CaretColumn            
        # reinsert the text            
        $editor.InsertText($SelectedText)            
        $EndLine =  $editor.CaretLine            
        $EndColumn = $editor.CaretColumn            
        # restore the selection            
        $editor.select($StartLine, $StartColumn, $EndLine, $EndColumn)             
        $reverse =  $CaretLine -eq  $StartLine -and $caretColumn -eq $StartColumn            
    }            
    else            
    {            
        $StartLine =  $EndLine = $LineCount            
        $StartColumn = $EndColumn = $editor.GetLineLength($EndLine) + 1            
        $reverse = $False            
    }            
                
    if (  $EndLine -lt  $LineCount)            
    {            
        $outputLine = $EndLine + 1            
        $outputColumn = 1            
        $NeedsNewLine = $False            
    }            
    else            
    {            
        $outputLine = $EndLine            
        $outputColumn = $EndColumn            
        if ($EndColumn -ne 1)            
        {            
            $NeedsNewLine = $True            
            $outputColumn = $editor.GetLineLength($EndLine) + 1            
        }            
        else            
        {            
            $NeedsNewLine = $False            
        }            
    }            
@"
DisplayName:     $($psIse.CurrentFile.DisplayName) 
LineCount:       $LineCount

CaretLine:       $CaretLine
CaretColumn:     $caretColumn
CaretLineLength: $CaretLineLength
CaretAtLineEnd:  $CaretAtLineEnd
CaretInLastLine: $CaretInLastLine

hasSelection:    $hasSelection
reverse:         $reverse

outputLine:      $outputLine
outputColumn:    $outputColumn
NeedsNewLine:    $NeedsNewLine
"@            
}            
            
Get-InfoAboutCurentFilesEditor

Montag, 29. März 2010

How to Organize Modules you Develop in Projects

Today I want to tell about the ways I organise my modul development.

When you start to develop PowerShell modules it is relative easy. Just add a folder under
(Split-path $profile) + '\Modules'            

say MyMod.
Then put a file MyMod.psm1 into it

Write-host "mymod loaded"


When you type ipmo Mymod, which is the alias for Import-Module you get


mymod loaded


With rmo Mymod , which is the short for Remove-Module you get rid of your module.

To check that it is removed, you can type
gmo or gmo Mymod, which is the alias for Get-Module

Now you shouldn't see it anymore.

Here I'm not going to tell you, what to put into your module file.

Best link for this I know is this post from Bruce Payette.

My focus here is, how to organise your system, when you have written something usefull and uploaded your module to some project.

I guess that you checkout your module from the project to some place, which is not in your modules folders. To ckeck where your system searches for modules just type

$env:PSModulePath -split ';'


Next I tried to be clever. I put the following into my profile:

$env:PSModulePath += ";\D:\MysharedProject\modules"


Now I can load the modules from this project by simple calles of ipmo myModule.

It really took some time to discover that I was too clever.

I'm using ISE for nearly all my PowerShell task and some time ago I discovered the menu New PowerShell Tab with the short-cut CTRL+T.

Each time you invoke this, you get a new PowerShell session and your PowerShell Profiles are executed.

But all these PowerShell session live in your current Windows session and each time the PSModulePath variable of the Windows environment will be modified. It gets longer and longer.

OK here now my final solution, this is the start of my profile.ps1

write-host "================== generall ($env:USERDOMAIN.$env:username) ==========================="            

$AdditionalModulPathes = @(
"D:\someProjectBleedingEdge\Modules"
"D:\someProjectRelease\Modules"
# "D:\MyCopyOfSomeProject\Modules"
)


foreach ($path in ($AdditionalModulPathes| Get-unique) )
{
if (($env:PSModulePath -split ';') -notcontains $path)
{
$env:PSModulePath += ";" + $path
}
}

# $env:PSModulePath -split ';'



Now I modify the evironment only once.
And here is the location, where I select whether I use the stable release, the current development version or my own unpublished work.

I hope this give you some ideas.

Bernd

BTW: ISE-Cream has reached release 0.1
If you are thinking about extending ISE, take a look at it

Donnerstag, 25. März 2010

PowerShell modules are funny guys

Ed Wilson says Windows PowerShell 1.0 was the vision, Windows PowerShell 2.0 is the reality [ from the preface of LeeHolmes Windows PowerShell Cookbook
I dare say PowerShell 2.0 ISE and Modules are still a vision.

When a module depends on a another module like SQLISE on ICECreamBasic or WPK it seems natural
to use within the .psm1 file
import-module ISECreamBasic            
import-module SQLParser
import-module adolib
import-module WPK


When I write a second module OracleIse, I can do similar

import-module ISECreamBasic            
import-module OracleClient
import-module WPK


Seems OK so far.

Next modules can be removed using Remove-module and that fires even an event to do some clean up as removing ISE addons menu items

$mInfo = $MyInvocation.MyCommand.ScriptBlock.Module            
$mInfo.OnRemove = {
Write-Host "$($MyInvocation.MyCommand.ScriptBlock.Module.name) removed on $(Get-Date)"
Remove-IseMenu OracleIse
}


Now emove on of these modules an see, which modules are left using

get-module            


You see, that the removed modul removed the modules imported within too, without tribute to the fact that the other module depends on WPK and ISECreamBasic too.

Conclusion. Better do not use import-module to import module from within your modules. Import the needed modules in advance.

Have some fun trying to find work arounds for this issue.

Bernd

Removing a specific Item from a Powershell ISE Addon menu

Well in ISECreamBasic I had written the function Remove-IseMenu to remove Toplevel menus.
Thanks to Shay Levi and Jaykul it became a nice advanced function with parametersets.

You can find the code in the ISE-Cream project

Just when I finished writing the header comments Ravi wanted to use the function not restricted to toplevel menu items.

First attemps tried to search the tree, but there can be more subitems with the same name hidden in the menu structure. To get it clear I designed the following function, which requires the complete path to the item to delete:

function Remove-IseMenuItem {            

$submenu = $psise.CurrentPowerShellTab.AddOnsMenu.Submenus

for ($j = 0; $j -lt $args.count; $j++)
{
$name = $args[$j]
$count = $submenu.count
#Write-host "arg0: $name $count"
for ($i = 0; $i -lt $submenu.count; $i++)
{
$found = $false
if ($Submenu[$i].DisplayName -eq $name)
{
#Write-host "found toplevel menu $name"
$found = $True
if ( $j -eq ($args.count - 1))
{
Write-host 'Removing'
$null = $submenu.remove($Submenu[$i])
}
else
{
$submenu = $Submenu[$i].submenus
}
break
}
}
if (! $found)
{
Write-host "Menuitem not found"
break
}

}
}

Remove-IseMenuItem Edit Pad

# Remove-Child $Submenu[$i] $Name | out-null



But this looks like an old PowerShell V1 coding style. It doesn't check that all arguments are strings. Please can someone show me, how to set up a PowerShell V2 advanced function parameter declaration for this.

Sonntag, 14. März 2010

PauerSchell Bernd joined SQLPSX

Hello database and PowerShell folks,

some days ago Chad Miller released SQLIse and soon afterwards Steven Murawski joined the SQLPSX project.

From the SQLIse project you can learn a lot about using PowerShell modules and building GUI with WPK. SQLIse uses System.Data.SqlClient, that is Ado.NET to access databases.

In the past I did some unpublished work using System.Data.OracleClient aka ODL on the database side.
In the old CTP3 days I joined the PowerShell ISE-Cream project, which did suffer a bit by the incompatible changes, which came with the PowerShell V2 RTM version.

But motivated by the execellent postings of Ravikanth Chaganti about PowerShell remoting, we began to revive that project and I learned a lot about working with multiple tabs (= PowerShell Sessions) and tuning the addons-menu.

Now I joined SQLPSX too.

I'm going to add the Connect and Invoke-ExecuteSql functions adapted to Oracle the next days.

The interface to procedure calls will take a bit longer as the coresponding SQL-Server functions aren't yet called by menu in the current version.

And as far as I know there is nothing comparable to SMO for Oracle.

One of the features I miss most on the current Oracle tools, is the fact, that they do help to display multiline fields in a wellformatted manner. Grid views tend to show only the first line and text views loose alignment. With PowerShell's Format-List cmdlet and Steves 'Result to variable' option, we can do better.

That's for now database folks, I have to do some PowerShell basics.

Bernd

Sonntag, 14. Februar 2010

1st improvement to Add-IseMenu

I hope that all users of Powershell V2 did try ISEpack from the PowerShellPack.

In the ISEpack module there is a function Add-IseMenu for creating addon menus.

On of its shortcomings is that it is not tolerant in case when a short-cut is alredy in use.

Just replace
$m = $iseMenu.Submenus.Add($itemName, $scriptBlock, $_.ShortcutKey)            

with
try {            
$m = $iseMenu.Submenus.Add($itemName, $scriptBlock, $_.ShortcutKey)
}
catch
{
Write-Host "Shortcut $($_.ShortcutKey) already in use. Menu item created without shortcut"
$m = $iseMenu.Submenus.Add($itemName, $scriptBlock, $null)
}

and that know-all behaviour is past. Now in case of clashes, it just creates the menu item without the short cut and emits a message.

For the second shortcoming, no control about the order of the items, I have not yet a compatible idea.

Bernd

Which files are loaded in PowerShell ISE

Here is a small function to give you information about the state of the files you have loaded into the different tabs and editors of ISE:

function Get-ISELoadedFiles () {            
$tabcount = 0
foreach ($Tab in $psise.PowerShellTabs)
{
if ($Tab -eq $psise.CurrentPowerShellTab) { $currentTab = '*' } else { $currentTab = ' ' }
$filecount = 0
if ($tab.CanInvoke) { $tabmarker = " $tabcount "} else { $tabmarker = "($tabcount)"}
"{0} -----{1} {2} ----- {3}" -f $currentTab, $tabmarker, $Tab.DisplayName, $tab.Prompt
$Tab.Files | %{
if ($_ -eq $psIse.CurrentFile) { $currentFile = '*' } else { $currentFile = ' ' }
if ($_.IsSaved) {$filemarker = "$filecount " } else {$filemarker = "$filecount*" }
"{0} {1} {2}" -f $currentFile, $filemarker, $_.fullpath
$filecount++
}
$tabcount++
}

}



It seems to be a little difficult to find out whether a tab is local or remote and if remote to which machine it is connected. Please drop a coment, if you have hints.

Thanks

Bernd
(or on twitter @bernd_k)

Sonntag, 31. Januar 2010

Out-ISEFile (V 0.9)

Just read the following tweet:

@MaxTrinidad Need the path to the various profile scripts on a system? Try $profile.psextended | Format-List (Try it in #PowerShell ISE too)

from @alexandair.

As I'm using ISE all day long, I tried it immedeatly and here is my result:
AllUsersAllHosts : C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1
AllUsersCurrentHost : C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShellISE_pro
file.ps1
CurrentUserAllHosts : C:\Users\berndk.MMEDVNT\Documents\WindowsPowerShell\profile.ps1
CurrentUserCurrentHost : C:\Users\berndk.MMEDVNT\Documents\WindowsPowerShell\Microsoft.PowerShe
llISE_profile.ps1



Oops again the PowerShells f***ing wrapping behavior. It's time to write a work around:

function Out-IseFile            
{

[CmdletBinding()]
param (
[Parameter(Position = 0, Mandatory = $True, ValueFromPipeline = $True)]
$msg,
[Parameter(Position = 1, Mandatory = $False, ValueFromPipeline = $False)]
$path = $null,
[switch]$fl
)
if ($fl)
{
$msg = $msg | Format-list | out-string -width 2000
}

$count = $psise.CurrentPowerShellTab.Files.count
$null = $psIse.CurrentPowerShellTab.Files.Add()
$Newfile = $psIse.CurrentPowerShellTab.Files[$count]
if ($path)
{
$NewFile.SaveAs($path)
$NewFile.Save([Text.Encoding]::default)
}
$Editor = $Newfile.Editor
#$Editor.SetCaretPosition($Editor.LineCount, 1)

$ar = $msg -split "`r`n" | %{ $_ -replace '\s*$', '' }

$msg = $ar -join "`r`n"

$msg = $msg + "`r`n"
$Editor.InsertText($msg)
$Newfile

}


$null = $profile.psextended | out-IseFile -fl



To use it just type:
$null = $profile.psextended | out-IseFile -fl


Please note: this is work in progress.
The main trick is to use Out-String with a long width parameter, that suppresses the unwanted wrapping.
For some reason (I guess it's just what we call in German Gedankenlosigkeit) Out-String emits trailing blanks. I included code to get rid of it.

Because Format-List seams rather frequent, I added the fl switch.

Remeber when ISE-Output pane behaves naughty ( and that is quite often) just send your output to a fresh editor. That makes it easy to edit and save it, if you want.

Have fun extending ISE.

Bernd

PS: Thanks to JS who made it extendable.

Sonntag, 27. Dezember 2009

Small Get-Process Puzzle

Hello PowerShell folks,

here I have a small puzzle for you. Please start only one instance of PowerShell odr PowerShell_ISE and run the following script.

$p1 = get-process powershell*             
$p2 = get-process powershell*

$p1
$p2

$p1 -eq $p2

Compare-Object $p1 $p2 -IncludeEqual


This time I'm not confuesed, that Compare-Object tells that both processes are equal. This time I wonder why $p1 is not equal To $p2.

When you invoke $p1 a number of times, you will see that the value CPU(s) increases. My natural expectation here is same PID same process.

Is this a PowerShell or a .NET issue ?
Do I better keep using WMI?

I get the rather strange feeling 'The more I learn, the less I know'.

Bernd

Donnerstag, 26. November 2009

And now using the data to generate sql INSERT-statements

Before SQL-Serve 2008 sql bulks of SQL Insert-Statements are so redundant, that they are not readable.
Of corse, if you are too clever you ommit the column list after INSERT INTO.
Try it and learn it the hard way.

One of my common tasks is generating Insert Statements. Perhaps this way:


$list = (             
( 1, 'PS', 'PowerShell is the most inovative scripting language'),
( 2, 'Python', 'has the most concise formating'),
( 3, 'Algol60', 'the mother of quoted identifiers'),
( 4, 'Algol68', 'the root of array slicing'),
( 5, 'c#', 'if only you were caseinsentitiv casesensitivity is ORACLE''s greates fault'),
( 6, 'SQL', 'has an Insert syntax which is worse than Street Basic''s Data-Statement
(where we put the assembler code you remember)'
)
)

foreach ($item in $list)
{
$id, $code, $note = $item
$note = $note -replace "'", "''" # you have to double embedded apostrophes
"insert into Computer_Languages ( Id, Code, Note) values ( $id, '$code', '$note')"
}

Sonntag, 25. Oktober 2009

Hello ISEpack

Hello PowerSheller Users,
now that Windows 7 is available and the most important event of the year PowerShell v2 Virtual Launch Party is history and James Brundage has buried as under tons of new functions in the PowerShell Pack
hopefully the last installations of PowerShell V2 CTP are replaced by the V2 RTM or V2 RC if you have a downgrade system.

ISE the Integrated Scripting Environment provides Windows conform copy & paste shortcuts. Thanks.

Any case, if you are completely new to PowerShell, it is better if you start with some GUI tool perhaps the free PowerGui or the commercial PowerShell Plus v3.0 , which have a lot of Intellisense build in. If you are interessted inother alternatives I recommend install Shay Levy's PowerShell Toolbar
. The link to the download is a little hidden, just above the comment section. Then go to resources | Script Editors.

These tools are kind of studios. They have some start-up time additional to that caused by your profile scripts and they try to help you in avoiding making mistakes by adding intellisense.

ISE is somewhat other. When you start it for the first time and scan through its menus you get the strong impression that there is something missing. For example: print, recently used files, ....

You are right, but there is something you don't see until you run some suitable script or import a module. ISEPack from the PowerShell Pack is one of these Modules:

import-module isepack

Afterwards the Add-ons menu appears. That is the magic location where you can extend ISE with all kinds of things you can sensibly do. And even some more.

There is an older Code Plex Project PowerShell ISE-Cream
which stagnated the last month due to PowerShell V2 CTP3 - V2 incompatibilities. I hope we will come back to life now.

My advice is please study ISEpack first and try ISE-Cream later. ISE-Cream is open and you too can contribute.

But now let us explore ISEPack a bit.

pushd "$(split-path $profile)\modules\isepack"         
Get-ChildItem


The most important file here is IsePack.psm1 . Here you find the code that constructs the add-ons menu.

You have qualms to modify JB's code.

No problem, you leave it as it is and add to the menu in another script:

Add-IseMenu -Name "My Extensions" @{                      
"Save File AS ANSI" = { $psISE.CurrentFile.Save([Text.Encoding]::default) } |
Add-Member NoteProperty ShortcutKey "ALT+Shift+A" -PassThru
}

Please note that I use default here and not ascii. Ascii is 7-bit only an not suitable for the german and many other western European languages.

Damned I forgot to take my chance at the launch party to ask Jeffrey, why there is a value called default, which isn't used by default.

I hope this helps to take the very first steps into the word of ISE Extensions.

Bernd

Sonntag, 26. April 2009

poshcodegen

The sql-server part of poshcodegen is nearly complete. And I'm using it in daily work.

The oracle part is a bit harder. Revisiting some old code I stumbled too often about #ToDo Comments. So its going on a little slower than expected.

Thinking that you prefer viewing at some real code, I post one of the Orcale test functions in Poshcode. Perhaps someone finds it there, just as I found the orginal http://poshcode.org/1011 from Steven Murawksi.

If your daily job is running ad hoc queries and stored procedure calls against SQL-Server Databases you may find something useful.

If you know how to access another RDBMS please join the project.

If you find a bug please send feedback. This is a complex area and it was too easy to introduce faults. We don't have automatic testing yet, but there is a rather complete set of test stored procedures for SQL-Server and for Oracle.

The second pitfall: too often the functions run perfectly too hours, but starting a fresh PowerShell I get errors. Often this is causes by the need to keep our own connection strings secret.

But now something useful, as far as you use ORCLE:



download | new post

Donnerstag, 15. Januar 2009

ISE and Read-Host why not read from Commandpane.Editor

I really hope, that in the final PowerShell V2 there is a way to use Read-Host reading from Commandpane.Editor without any Prompt-Dialog.



Without this many interessting Custum Menue Extensions like this one
are slowed down by some additional GUI-Elements.



I do not want to isolate the prompt input from the command history.



I want to be able to clone ISQL/w or SQL Querry Analyzer or 1000 other 'inconceivable' things within ISE.



I want some jobs be done while xx-Studio still is loading.


This refers To Visual-Studio as well as Toad or Power-GUI or SQL-Management Studio.



Dont't panic.



Bernd


Mittwoch, 14. Januar 2009

Hint to test ISE-Extensions

I have some difficulties using regular expressions on the CRLF sequences within editor.Text

Using format-hex from Hex Dumper in Monad. I just need to select some text and can see that lines within the editors are CRLF delimited too

[char[]]$psise.CurrentOpenedFile.editor.SelectedText | format-hex


Mittwoch, 7. Januar 2009

ISE - Snippets Variant 2

Hello again

poetter postet some ISE Custom menue extensions at poshcode.

He displays a list and uses a prompt dialog to select the choice.

Well the list might get quite long and I tried a different approach: selecting the choice by either the selected text or by the text left to the cursor. Here the result, which is based on his code.


#requires -version 2.0
#
# ISE-Snippets module v 1.0
#
# DEVELOPED FOR CTP3
#
# See comments for each function for changes ...
#
#############################################################################################################
#
# As a shortcut for every snippet would be to much, I created Add-Snippet which presents a menu.
#
# Feel free to add your own snippets to function Add-Snippet but please contribute your changes here
#
#############################################################################################################
#
# Provides Code Snippets for working with ISE
#
# Add-Snippet - Presents menu for snippet selection
#
# Add-SnippetToEditor - Adds a snippet at caret position
#
#############################################################################################################


## Add-Snippet
#
#############################################################################################################
#
# Presents menu for snippet selection
#
#############################################################################################################
function Add-Snippet
{
$snippets = @{
"region" = @( "#region", "#endregion" )
"function" = @( "function FUNCTION_NAME", "{", "}" )
"param" = @( "param ``", "(", ")" )
"if" = @( "if ( CONDITION )", "{", "}" )
"else" = @( "else", "{", "}" )
"elseif" = @( "elseif ( CONDITION )", "{", "}" )
"foreach" = @( "foreach ( ITEM in COLLECTION )", "{", "}" )
"for" = @( "foreach ( INIT; CONDITION; REPEAT )", "{", "}" )
"while" = @( "while ( CONDITION )", "{", "}" )
"dowhile" = @( "do" , "{", "}", "while ( CONDITION )" )
"dountil" = @( "do" , "{", "}", "until ( CONDITION )" )
"try" = @( "try", "{", "}" )
"catch" = @( "catch", "{", "}" )
"catch [<error type>] " = @( "catch [ERROR_TYPE]", "{", "}" )
"finaly" = @( "finaly", "{", "}" )
}


$editor = $psISE.CurrentOpenedFile.Editor
if ( $editor.SelectedText.length -eq 0) {
$caretLine = $editor.CaretLine
$caretColumn = $editor.CaretColumn
$text = $editor.Text.Split(
"`n")
$line = $text[$caretLine -1]
$LeftOfCarret = $line.substring(0, $caretColumn - 1)
$parts = $LeftOfCarret.split(
"")
$len = $parts[-1].length
$start = $caretColumn - $len
$editor.select($caretLine, $start, $caretLine, $caretColumn )
}

$snippetName = $editor.SelectedText
$editor.insertText('')
Add-SnippetToEditor $snippets[$snippetName]
}

## Add-SnippetToEditor
##############################################################################################################
## Adds a snippet at caret position
##############################################################################################################
function Add-SnippetToEditor
{
param `
(
[string[]] $snippet
)

$editor = $psISE.CurrentOpenedFile.Editor
$caretLine = $editor.CaretLine
$caretColumn = $editor.CaretColumn
$text = $editor.Text.Split(
"`n")
$newText = @()
if ( $caretLine -gt 1 )
{
$newText += $text[0..($caretLine -2)]
}
$curLine = $text[$caretLine -1]
$indent = $curline -replace
"[^\t ]", ""
foreach ( $snipLine in $snippet )
{
$newText += $indent + $snipLine
}
if ( $caretLine -ne $text.Count )
{
$newText += $text[$caretLine..($text.Count -1)]
}
$editor.Text = [String]::Join(
"`n", $newText)
$editor.SetCaretPosition($caretLine, $caretColumn)
}

#Export-ModuleMember Add-Snippet


##############################################################################################################
## Inserts command Add Snippet to custom menu
##############################################################################################################
if (-not( $psISE.CustomMenu.Submenus | where { $_.DisplayName -eq
"_Snippet" } ) )
{
$null = $psISE.CustomMenu.Submenus.Add(
"_Snippet", {Add-Snippet}, "Ctrl+Alt+S")
}


Thanks and congratulation to Dmitry for delivering the new CTP 3 compatible Powergui version and telling in his blog about export html. I just tried this here for the code above.

The above code is ready for every days use. It is just a design study in programming the selection. Personally I don't use snippets in any editor while coding, just a question of personal taste.

In the long term I will use this to interactivly transform T-SQL into PL/SQL. I guess in the end, this will save a lot of my time.

Thanks to the PowerShell Team who did such a good and extendable job. A real christmas present.

Enjoy extending

Bernd