Tag Archives: ping

Give a Parameter a Default Value

Part II: http://tommymaynard.com/quick-learn-give-a-parameter-a-default-value-part-ii-2015/

If you’re into Windows PowerShell, then you probably think a little like me. You want to do things fast, and efficiently. There’s a reason we pound out commands and write scripts: we want to make the most of our time, and PowerShell let’s us do that. With that in mind, I decided I should modify a cmdlet I often use, so that using it takes less time, by default.

The Test-Connection cmdlet does for us what ping always has. It sends ICMP request packets to a remote computer or device. If the remote computer or device sends us a reply, then we know the device is up. It should be stated, that ICMP replies can be restricted so that a computer or device that is up, may not reply. Although I’ve opted to use Test-Connection for my example, this concept can be used with any number of other cmdlets and their parameters.

Let’s start by taking a look at the default output of the Test-Connection cmdlet. By default, Test-Connection will ping a given computer four times. If I were checking for latency, four replies would probably be better than one, but because I just want to know if the computer is up or down, a single reply is suitable.

PS C:\> Test-Connection -ComputerName bing.com

Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms)
------        -----------     -----------      -----------                              -----    --------
TOMMYMAYNA... bing.com        204.79.197.200                                            32       14
TOMMYMAYNA... bing.com        204.79.197.200                                            32       13
TOMMYMAYNA... bing.com        204.79.197.200                                            32       14
TOMMYMAYNA... bing.com        204.79.197.200                                            32       13

This cmdlet includes a -Count parameter, and so I could have used that, as -Count 1, so that my computer only sent a single packet. But remember, I want be fast and efficient — I don’t want type more to see less. I want to type the same and make things faster. To accomplish this, what I’ll do is change the default behavior of this command to only send one packet. These means I’ll need to make use of the $PSDefaultParameterValues variable.

The $PSDefaultParameterValues variable stores any modifications to the default values of any of our cmdlet’s parameters. Since I don’t have any modified default values, the variable has nothing to return.

PS C:\> $PSDefaultParameterValues
PS C:\>

In the example below, we’ll use the Add() method to add a key/value pair to the variable. The keys are anything in the Name property, and the values are anything in the Value property. There is a one-to-one ratio between keys and values. These are also referred to as hash tables, associative arrays, or a dictionary object.

After we’ve added our key/value pair, we’ll try Test-Connection again, as we did in the first example.

PS C:\> $PSDefaultParameterValues.Add('Test-Connection:Count','1')
PS C:\> $PSDefaultParameterValues

Name                           Value
----                           -----
Test-Connection:Count          1

PS C:\> Test-Connection -ComputerName bing.com

Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms)
------        -----------     -----------      -----------                              -----    --------
TOMMYMAYNA... bing.com        204.79.197.200                                            32       13

PS C:\>

As we can see, Test-Connection will now only ping a computer one time by default. Now, what happens when I do want to test for latency? I can use the -Count parameter and supply whatever number I want, so long as it’s 1 through 2147483647. Using zero or less, or 2147483648 will not work. I know, I tried.

You can read more information on the about_Parameters_Default_Values page here: https://technet.microsoft.com/en-us/library/hh847819.aspx.

Make Ping Accept Multiple Computers

Windows PowerShell, and an old-school command line tool favorite, collided today when I brainlessly typed the following:

PS C:\> ping computer1,computer2
Bad parameter computer2

This didn’t work, and as quickly as I realized my mistake, I thought, I’m going to have to fix it so ping can accept multiple computers.

There’s a couple ways I can do this, but my idea was to create an advanced function to do the work. I did that, but before I share the function, we should discuss what we could have done. We could have simply made an alias named ping that would run the Test-Connection cmdlet, a cmdlet that can handle a comma-separated list of computer names. Here’s an example of creating the alias and then using it to ping multiple computers.

PS C:\> New-Alias -Name ping -Value Test-Connection
PS C:\> ping computer1,computer2

Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms)
------        -----------     -----------      -----------                              -----    --------
TOMMYMS PC... computer1       10.10.10.30                                              32       1
TOMMYMS PC... computer2       10.10.10.31                                              32       1
TOMMYMS PC... computer1       10.10.10.30                                              32       1
TOMMYMS PC... computer2       10.10.10.31                                              32       1
TOMMYMS PC... computer1       10.10.10.30                                              32       1
TOMMYMS PC... computer2       10.10.10.31                                              32       1
TOMMYMS PC... computer1       10.10.10.30                                              32       2
TOMMYMS PC... computer2       10.10.10.31                                              32       2

The reason this works is because of command precedence. If an alias and a command line tool share the same name, the alias will always run when the name is entered.

Well, this wasn’t quite want I wanted. I thought instead, I would make a wrapper around Test-Connection, called Test-TMConnection that would include a switch parameter (-Ping) that would return the standard ping results. I’ll dump in the function below and then we can walk though what it does.

Function Test-TMConnection {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true)]
        [string[]]$ComputerName,

        [switch]$Ping
    )

    Begin {
    } # End Begin

    Process {
        If ($Ping) {
            ForEach ($Computer in $ComputerName) {
                ping $Computer
            }
        } Else {
            Test-Connection -ComputerName $ComputerName
        }
    } # End Process
} # End Function

Here’s how this works: The function is called by entering Test-TMConnection, the -ComputerName parameter, and then either one computer name, or a comma-separated list of computers. If the -Ping parameter is not used, it will run the standard Test-Connection cmdlet against the computer(s), like we saw in the alias example above. If -Ping is included, it will loop though the computers, using each one with ping. Here’s an example that includes the -Ping parameter.

PS C:\> Test-TMConnection -ComputerName computer1,computer2 -Ping

Pinging computer1.mydomain.com [10.10.10.30] with 32 bytes of data:
Reply from 10.10.10.30: bytes=32 time=2ms TTL=121
Reply from 10.10.10.30: bytes=32 time=1ms TTL=121
Reply from 10.10.10.30: bytes=32 time=1ms TTL=121
Reply from 10.10.10.30: bytes=32 time=1ms TTL=121

Ping statistics for 10.10.10.30:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 1ms, Maximum = 2ms, Average = 1ms

Pinging computer2.mydomain.com [10.10.10.31] with 32 bytes of data:
Reply from 10.10.10.31: bytes=32 time=1ms TTL=121
Reply from 10.10.10.31: bytes=32 time=2ms TTL=121
Reply from 10.10.10.31: bytes=32 time=1ms TTL=121
Reply from 10.10.10.31: bytes=32 time=1ms TTL=121

Ping statistics for 10.10.10.31:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 1ms, Maximum = 2ms, Average = 1ms

Important: Keep in mind, that if you were to use something like this, that you’ll be giving up other parameters that are included with ping and Test-Connection. This includes -t with ping, and -Count, and -Source with Test-Connection. In the end, the ping alias might be the better option.

Add CMD’s ver to PowerShell

One of the great things about Windows PowerShell is that it can run Windows native command line tools, such as ping, ipconfig, and others. There are times, however, when there are exceptions. While recently working in the console, I brainlessly entered ‘ver’ (without the quotes), and it didn’t return what I expected. Instead of printing ‘Microsoft Windows [Version 6.3.9600]’ to the console, it reported that ver wasn’t recognized.

PS C:\> ver
ver : The term 'ver' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ ver
+ ~~~
    + CategoryInfo          : ObjectNotFound: (ver:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

While I wouldn’t recommend opening CMD to run the command, because seriously get out of that habit already, you can switch to CMD from inside the PowerShell console, as demonstrated below.

PS C:\> cmd
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\>ver

Microsoft Windows [Version 6.3.9600]

C:\>exit
PS C:\>

Still, this wasn’t quite as native as I wanted. For whatever reason, I wanted to type ver, and get the identical output I was used to seeing,… regardless of the fact that the ver output doesn’t really tell me much.

The first thing I did was launch the ISE and create an alias for ver. Keep in mind, that you may need to add -ErrorAction SilentlyContinue to the New-Alias cmdlet, if you run the script more than once inside the ISE. The problem here is that you’ll receive an error if you try and create an alias that is already being used. Either that, or you can add the -Force parameter and make New-Alias act like Set-Alias (and overwrite the alias even though it’s not really changing it).

New-Alias -Name ver -Value Get-TMVersion

Next, I constructed a function called Get-TMVersion that the alias ver would use. Inside the function, I created a single variable, $OS, and assigned it the results of a Get-CimInstance command. If for some reason you’re still using PowerShell 2.0, this can be replaced by the Get-WmiObject equivalent: Get-WmiObject -Class Win32_OperatingSystem.

Function Get-TMVersion {
    $OS = Get-CimInstance -ClassName Win32_OperatingSystem
}

Once I have this data stored in a variable, I can begin checking for a value in the variable, and then, building out my results to match the native Windows command. The If statement checks to see if the Name property of $OS begins with the string Microsoft Windows. Providing it does, it sets a second variable, $Version, as seen in the example below. Once that’s complete, it then echos a blank line, the $Version variable, and then echos a second blank line. At this point, $Version should be identical to the ver command’s standard output.

Function Get-TMVersion {
    $OS = Get-CimInstance -ClassName Win32_OperatingSystem
    If ($OS.Name -like 'Microsoft Windows*') {
        $Version = "Microsoft Windows [Version $($OS.Version)]"
    }
    Write-Output -Verbose `r`n$Version`r`n
}

Here’s the function in action.

PS C:\> ver

Microsoft Windows [Version 6.3.9600]

PS C:\>

Boring, but it works. I should note that this function would probably be best served to include some error checking, in case setting the $OS variable errors out. In addition, I suspect there are probably other ways to produce the same resul–… (pause, keyboard keys clicking) …ugh, here’s a couple variations of yet another, simpler way.

PS C:\> cmd /c ver

Microsoft Windows [Version 6.3.9600]
PS C:\> cmd /c ver;echo ''

Microsoft Windows [Version 6.3.9600]

PS C:\>

It seems I could have just dropped a tiny bit of text into my function and called it a day. If you’ve ever read anything else I’ve written and posted, then you may have noticed a pattern. I seem to do things the hard way, long before I figure out a simpler way. I like it that way, though. If anything, it keeps me thinking, and therefore, improving my PowerShell skills overall.

Function Get-TMVersion {
    cmd /c ver
    Write-Output -Verbose ''
}