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

Using Proxy Commands in PowerShell

Jeffrey Snover just posted a great article on how to use Proxy Commands in CTP3. He also built a module called MetaProgramming that makes this much easier. I was able to take what he did and created a proxy command for get-childitem and added two switch parameters, -containersOnly and -NoContainersOnly.

I posted the code up on PoshCode here.

  1. Function Get-ChildItemProxy {
  2. [CmdletBinding(DefaultParameterSetName='Items', SupportsTransactions=$true)]
  3. param(
  4.     [Parameter(ParameterSetName='Items', Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
  5.     [System.String[]]
  6.     ${Path},
  7.  
  8.     [Parameter(ParameterSetName='LiteralItems', Mandatory=$true, Position=0, ValueFromPipelineByPropertyName=$true)]
  9.     [Alias('PSPath')]
  10.     [System.String[]]
  11.     ${LiteralPath},
  12.  
  13.     [Parameter(Position=1)]
  14.     [System.String]
  15.     ${Filter},
  16.  
  17.     [System.String[]]
  18.     ${Include},
  19.  
  20.     [System.String[]]
  21.     ${Exclude},
  22.  
  23.     [Switch]
  24.     ${Recurse},
  25.  
  26.     [Switch]
  27.     ${Force},
  28.  
  29.     [Switch]
  30.     ${Name},
  31.    
  32.     [Switch]
  33.     ${ContainersOnly},
  34.    
  35.     [Switch]
  36.     ${NoContainersOnly}
  37.     )
  38.  
  39. begin
  40. {
  41.     try {
  42.         $outBuffer = $null
  43.         if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer) -and $outBuffer -gt 1024)
  44.         {
  45.             $PSBoundParameters['OutBuffer'] = 1024
  46.         }
  47.         $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Get-ChildItem', [System.Management.Automation.CommandTypes]::Cmdlet)
  48.        
  49.         if ($ContainersOnly)
  50.         {
  51.             [Void]$PSBoundParameters.Remove("ContainersOnly")
  52.             $scriptCmd = {& $wrappedCmd @PSBoundParameters | Where-Object {$_.PSIsContainer -eq $true}}
  53.            
  54.         } elseif ($NoContainersOnly)
  55.                {
  56.                    [Void]$PSBoundParameters.Remove("NoContainersOnly")
  57.                    $scriptCmd = {& $wrappedCmd @PSBoundParameters | Where-Object {$_.PSIsContainer -eq $false}}
  58.                }   
  59.         {
  60.             $scriptCmd = {& $wrappedCmd @PSBoundParameters }
  61.         }
  62.        
  63.  
  64.        
  65.         $steppablePipeline = $scriptCmd.GetSteppablePipeline()
  66.         $steppablePipeline.Begin($PSCmdlet)
  67.     } catch {
  68.         throw
  69.     }
  70. }
  71.  
  72. process
  73. {
  74.     try {
  75.         $steppablePipeline.Process($_)
  76.     } catch {
  77.         throw
  78.     }
  79. }
  80.  
  81. end
  82. {
  83.     try {
  84.         $steppablePipeline.End()
  85.     } catch {
  86.         throw
  87.     }
  88. }
  89. <#
  90.  
  91. .ForwardHelpTargetName Get-ChildItem
  92. .ForwardHelpCategory Cmdlet
  93.  
  94. #>
  95.  
  96. }
downloadThis Script brought to you by PoshCode