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

Pinging a Server from a Server you are not logged in to

I recently had a unique situation in which I needed to see if 4 different servers could ping a specific IP Address. Very often, we use win32_pingstatus to see if a remote machine is responding or not. But in this case, I needed to know if a remote machine could ping another remote machine. Routing was actually set up so that I could not ping the second remote machine from my laptop.

What’s cool is that you can use the –computername parameter in get-wmiobject when you look at win32_pingstatus.

image

I did change the name in a text editor to remote1 just for the sake of demo and public screen shots.

So if you wanted server remote1 to ping server remote3 you could do something like this:

Get-WmiObject Win32_pingstatus –filter “Address =’remote3’” –computername remote1.

Pinging a Server from a Server you are not logged in to

I recently had a unique situation in which I needed to see if 4 different servers could ping a specific IP Address. Very often, we use win32_pingstatus to see if a remote machine is responding or not. But in this case, I needed to know if a remote machine could ping another remote machine. Routing was actually set up so that I could not ping the second remote machine from my laptop.

What’s cool is that you can use the –computername parameter in get-wmiobject when you look at win32_pingstatus.

image

I did change the name in a text editor to remote1 just for the sake of demo and public screen shots.

So if you wanted server remote1 to ping server remote3 you could do something like this:

Get-WmiObject Win32_pingstatus –filter “Address =’remote3’” –computername remote1.

Using a Color Dialog to choose colors for ISE

image

Currently, there are no default UI options to set the color for the Script Pane, the Command Pane, or the Output Pane. However, these can all be changed using $psISE.

I wrote a few functions to help with this.

function Set-CommandBackPaneColor {
param
(
    [parameter(Mandatory=$true,ValueFromPipeline=$true)]
    $color
)
    $psise.Options.CommandPaneBackground = $color
}

function Set-OutputPaneColor {
param
(
    [parameter(Mandatory=$true,ValueFromPipeline=$true)]
    $color
)
    $psise.Options.OutputPaneBackground = $color
    $psise.Options.OutputPaneTextBackground = $color
}

function Set-ScriptPaneColor {
param
(
    [parameter(Mandatory=$true,ValueFromPipeline=$true)]
    $color
)
    $psise.Options.ScriptPaneBackground = $color
}
				   
  

Automatically generated with a custom version of Write-CommandBlogPost

Set-OutputPaneColor sets two options, OutputPaneBackground and OutputPaneTextBackground. I have found that I like to have these the same, but you can easily separate them out if you like.

The last little tidbit is figuring out how to get a color picker rather than typing in the name of the color. We can accomplish this with a little Winforms action.

function Get-Color {
    $colorDialog = new-object System.Windows.Forms.ColorDialog 
    $colorDialog.AllowFullOpen = $false
    [void]$colorDialog.ShowDialog()
    $colorDialog.Color.Name
}
				   
  

Automatically generated with a custom version of Write-CommandBlogPost

This will return the name of the color that was picked

image

After clicking on Red, I get the following output

image

So now we can tie this all together with one final line to add a custom menu to ISE

[void]$psISE.CustomMenu.Submenus.Add("Output Pane Color", {Get-Color | Set-OutputPaneColor},$null)

I just passed in Null because I didn’t want a keyboard shortcut, but you can use one pretty easily.

So now I get the following:

image

I could set up Menus to set other color options for the script and command panes as well, but I figure that is enough screenshots to make the point.

The other custom commands are from Karl Prosser. I highly recommend you take a look at them as well. Very useful.

So there is one (not so subtle) flaw in the get-color function. It does not always place the color dialog on the top, so sometimes I have to Alt-Tab over to it. There is probably some nifty way with winforms to make it show up on top all the time, but I figured I would get this out there and then work on that little part.

Secondly, not all the colors work right now.

PowerShell shortcut for Terabyte and Petabyte

In V1, we had KB, MB, and GB. Now we get TB and PB

image

Pretty slick.

PowerShell shortcut for Terabyte and Petabyte

In V1, we had KB, MB, and GB. Now we get TB and PB

image

Pretty slick.

PowerShell Remoting on Windows 2008 R2 Server Core

I've been working on building out some 2008 R2 Core servers the last couple days and of course I wanted to get PowerShell up and running on them.  First of all, to install the PowerShell feature you need to run this command

start /w ocsetup MicrosoftWindowsPowerShell

Note that ocsetup is case sensitive and you need to get the name of the feature and/or role exactly right.

Once you get the feature installed, you can launch powershell from the cmd prompt by using the full path to c:\windows\system32\windowspowershell\v1.0\powershell.exe.

Now that we have PowerShell V2 running, we can get-started with Remoting. To enable V2 remoting, there is a built-function called Enable-PSRemoting which typically is all you need. However, there is a known issue with Windows 7 Beta x64 systems where WOW components are not installed - a category which server core falls into.

If you try to enable remoting, you will get an error about a corrupted plugin in WSMAN.

To work around this, you need to remote a registry value. Run the following command

remove-item HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN\Plugin\Microsoft.PowerShell32

After that, you can run Enable-PSRemoting and you are good to go.

Write-CommandBlogPost

Thought I would share my ISE profile and test out Write-CommandBlogPost in Live Writer with Doug Finke’s Live Writer Add-In

Microsoft.PowerShellISE_profile.ps1

Synopsis:

Creating and using a Windows PowerShell profile
Here's Microsoft.PowerShellISE_profile.ps1:
function Set-File {
param
(
    [parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [string]
    $file
)

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

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
}

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

$psise.options.CommandPaneUp = $true
$psise.options.fontname = "Consolas"
$psise.options.fontsize = 16

[void]$psIse.CustomMenu.Submenus.Add("_Function Template", {New-FunctionTemplate},"Alt+F")
[void]$psISE.CustomMenu.Submenus.Add("Region 1", {invoke-region 1 },'ctrl+1')
[void]$psISE.CustomMenu.Submenus.Add("Region 2", {invoke-region 2 },'ctrl+2')
[void]$psISE.CustomMenu.Submenus.Add("Region 3", {invoke-region 3 },'ctrl+3')
[void]$psISE.CustomMenu.Submenus.Add("Region 4", {invoke-region 4 },'ctrl+4')
[void]$psISE.CustomMenu.Submenus.Add("Region 5", {invoke-region 5 },'ctrl+5')
[void]$psISE.CustomMenu.Submenus.Add("Current Line", {invoke-caretline},'f7')

$docs    =  $(resolve-path "$Env:userprofiledocuments")
$desktop =  $(resolve-path "$Env:userprofiledesktop")
$myMod   =  $(resolve-path $($Env:PSMODULEPATH -split ";")[0])

Automatically generated with a custom version of Write-CommandBlogPost

Advanced Functions Support -confirm

I was using the "Module" Module to generate some scripts and started looking at SupportsShouldProcess , a parameter the CmdletBinding attribute. Turns out with V2 it is very simple to implement some sanity checking in the functions we write so people don't go and blow their pinky tow off with a shotgun. So the trick is a simple IF statement in the PROCESS Block of your script or function. There is a variable called $PSCmdlet that you can use to determine if the user entered the -confirm or -whatif switch. The first parameter in the ShouldProcess method is the target and the second parameter is the operation. Note that if the operation is not specified, it will default to the name of the function.
supportshouldprocessfunction
Here I have a parameter called $test and if I type -confirm it will ask me if I want to "Destroy Everything" on target "Whatever the value of $test is" The ISE gives a nice Windows dialog box with the options when I type "Get-Something "That you can see" -confirm confirmdestroytheworld