A Method to the Add-Member Madness

I have been writing a script where, for all intents and purposes, I basically needed to be able to create a class. I wanted to be able to repeatedly create a new-object of a certain type that had a certain set of properties and methods. Even in PowerShell V2, there is still no "New-Class" cmdlet, but we can fake it well enough for practical purposes. That is at least for my practical purposes. There is a lot of information on the web about using Add-Member and essentially creating property bags as shown in the code below.

001
002
003
004
005
006
007
008
009
$obj = new-object psobject 
                                                                     
$obj | Add-Member -MemberType noteproperty `
                  -Name FirstColor `
                  -Value orange                            

$obj | Add-Member -MemberType noteproperty `
                  -Name SecondColor `
                  -Value Yellow

From here we get a PSObject with two properties, FirstColor and SecondColor. So what can we do for methods? The Add-Member cmdlet has a parameter called MemberType. In the example above, I used two NoteProperties. There are several other possibilities that can be used here as well. I would argue, the second most useful MemberType would be ScriptMethod. ScriptMethods have a name, just like a NoteProperty, and a value, but the value is of type [ScriptBlock].

One thing to be aware of when using ScriptMethods is the automatic variable $this. The $this variable refers to the current object. It is similar to the "this" keyword in C#. Probably the best way to explain is with an example. First I will build a ScriptBlock using a here string and call the [ScriptBlock]::Create() Method. Finally, the ScriptBlock can be added as a value for the new member that is called "ChangeFirstColor"

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
$code = @'
param($color)
$this.FirstColor = $color
'@


$sblock = [scriptblock]::create($code)

$obj = new-object psobject 
                                                                     
$obj | Add-Member -MemberType noteproperty `
                  -Name FirstColor `
                  -Value orange                            

$obj | Add-Member -MemberType noteproperty `
                  -Name SecondColor `
                  -Value Yellow
                 
$obj | Add-Member -MemberType scriptmethod `
                  -Name ChangeFirstColor `
                  -Value $sblock

So now we have a method called ChangeFirstColor. Yes, we could just set the property to a new color, but suppose you wanted to put some logic and verification steps into it first. This is merely an example of what you could do. The other thing that is pretty cool is that ScriptMethods can take parameters. Notice I use the param statement in the ScriptBlock. You could also use $args but that drives me nuts and leads to confusion for the person that has to read code 6 months from now.

image

A Method to the Add-Member Madness

I have been writing a script where, for all intents and purposes, I basically needed to be able to create a class. I wanted to be able to repeatedly create a new-object of a certain type that had a certain set of properties and methods. Even in PowerShell V2, there is still no "New-Class" cmdlet, but we can fake it well enough for practical purposes. That is at least for my practical purposes. There is a lot of information on the web about using Add-Member and essentially creating property bags as shown in the code below.

001
002
003
004
005
006
007
008
009
$obj = new-object psobject 
                                                                     
$obj | Add-Member -MemberType noteproperty `
                  -Name FirstColor `
                  -Value orange                            

$obj | Add-Member -MemberType noteproperty `
                  -Name SecondColor `
                  -Value Yellow

From here we get a PSObject with two properties, FirstColor and SecondColor. So what can we do for methods? The Add-Member cmdlet has a parameter called MemberType. In the example above, I used two NoteProperties. There are several other possibilities that can be used here as well. I would argue, the second most useful MemberType would be ScriptMethod. ScriptMethods have a name, just like a NoteProperty, and a value, but the value is of type [ScriptBlock].

One thing to be aware of when using ScriptMethods is the automatic variable $this. The $this variable refers to the current object. It is similar to the "this" keyword in C#. Probably the best way to explain is with an example. First I will build a ScriptBlock using a here string and call the [ScriptBlock]::Create() Method. Finally, the ScriptBlock can be added as a value for the new member that is called "ChangeFirstColor"

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
$code = @'
param($color)
$this.FirstColor = $color
'@


$sblock = [scriptblock]::create($code)

$obj = new-object psobject 
                                                                     
$obj | Add-Member -MemberType noteproperty `
                  -Name FirstColor `
                  -Value orange                            

$obj | Add-Member -MemberType noteproperty `
                  -Name SecondColor `
                  -Value Yellow
                 
$obj | Add-Member -MemberType scriptmethod `
                  -Name ChangeFirstColor `
                  -Value $sblock

So now we have a method called ChangeFirstColor. Yes, we could just set the property to a new color, but suppose you wanted to put some logic and verification steps into it first. This is merely an example of what you could do. The other thing that is pretty cool is that ScriptMethods can take parameters. Notice I use the param statement in the ScriptBlock. You could also use $args but that drives me nuts and leads to confusion for the person that has to read code 6 months from now.

image

Posting PowerShell Code with Live Writer

Lee Holmes recently wrote a post on PowerShell Syntax Highlighting. I have been using Windows Live Writer for a while now and have used a variety of ways to post code snippets, functions, and scripts.

I really like the look and feel of Lee's output. Nice and clean, easy to copy and paste, line numbers and color coding. 

So of course I went and tried it using his script. I was able to copy and paste into word without a problem and get all the cool nice highlighting, but as soon as I tried to paste in Live Writer, it just pasted in what seemed to be raw text.

I went digging around and found an option in Live Writer called "Paste Special."

The default was "Thinned HTML."

image

Using "Keep Formatting" allowed me to paste in the code just as expected.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
function Set-File {
param
(
    [parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [string]
    $file
)

    $psise.CurrentOpenedRunspace.OpenedFiles.Add($file)
}

function invoke-caretline
{ 
    invoke-expression $([Regex]::Split($psISE.CurrentOpenedFile.Editor.text,"`r`n" )[$psISE.CurrentOpenedFile.Editor.caretline-1])
}


function invoke-region{
param
(
    [int] $num
)
    $ed = $psISE.CurrentOpenedFile.Editor
    $lines = [Regex]::Split($ed.text,"`r`n" )
    $foundfirst = -1
    $foundlast = -1

    for($count = 0;$count -le $lines.length-1;$count++)
        {
            if ($lines[$count].startswith("#region") -and $lines[$count].contains("@$num")) 
               { $foundfirst = $count;break}    
        }
       
    if($foundfirst -gt -1)
    {
        for ($count = $foundfirst; $count -le $lines.length-1;$count++)
        {   
            if ($lines[$count].startswith("#endregion") )
               {$foundlast = $count;break}    
        } # end For $lines
   
    if ($foundlast -gt -1)
     {
         $torun = ""
         $lines[$foundfirst..$foundlast] | % { $torun+=$_ + "`r`n"}
         invoke-expression $torun
     } # end if $foundLast
   
    } # End for $count
 
} # End Function Invoke-Region


function Insert-Text{
param
(
    [parameter(Mandatory=$true, ValueFromPipeline=$true)]
    [string]
    $text
)
    $currentFilePath = $psise.CurrentOpenedFile.FullPath
    $currentFile = $psIse.CurrentOpenedRunspace.OpenedFiles |
               where {$_.FullPath -eq $currentFilePath}
    $currentFile.editor.InsertText($text)
}

function New-FunctionTemplate{
param
(
    [parameter(Mandatory=$true, ValueFromPipeline=$true)]
    [string]
    $verb,
   
    [parameter(Mandatory=$true, ValueFromPipeline=$true)]
    [string]
    $noun   
)

$f = @"
function $Verb-$Noun {
param (
    [parameter(Mandatory=$true, ValueFromPipeline=$true)
    [string]
    $p1
)
begin {}
process {}
end {}
}
"@

    Insert-Text -text $f
}

I guess the next task is to write a plug-in for Jame's Write-CommandBlogPost