Tag Archives: Get-Command

Adding a Help Parameter to a Function

Edit: There’s a quick addition at the bottom of this post. I tried something else, it worked, and so I decided to include it.

I started writing a PowerShell function to replicate the work of an old executable called ICSWEEP. ICSWEEP “is a command-line utility to clear the Temporary Internet Files Cache and/or the TEMP files folder of ALL user profiles that are NOT in use when this command is executed.” ICSWEEP Information. I may or may not walk through the process of writing this function here; it’s to be determined. What I do want to discuss for sure, however, is the last switch in the above image. It’s /?.

We cannot add ? parameter to a function. Below is an image of the message when we attempt to do that in VS Code.

That’s right, right!? You do remember the $? variable. It stores the execution status of the last command as True or False. Instead of ? as a parameter, I used the value of Help. Therefore, someone can invoke my function and use -Help to get help with the function. But could they?

I sat there, wondering, can you create a parameter of a function so that it’ll return its own, comment-based help? It turns out you can. Here’s the early stage of this function. It consists of the comment-based help, a few parameters, and a small amount of code.

function Clear-UserTemporaryFile {
<#
.SYNOPSIS
    The Clear-UserTemporaryFile command ...
.DESCRIPTION
.PARAMETER <Parameter>
.EXAMPLE
.NOTES
    Name: Clear-UserTemporaryFile
    Author: Tommy Maynard
    Comments: --
    Last Edit: 12/13/2022 [1.0.0]
    Version: 1.0.0
#>
    Param (
        [Parameter()]
        [switch]$ALL,
        [Parameter()]
        [string]$TIF,
        [Parameter()]
        [string]$TMP,
        [Parameter()]
        [string]$SIZE,
        [Parameter()]
        [switch]$HELP
        
    )

    if ($HELP) {
       Get-Help -Name "$($MyInvocation.MyCommand.Name)"
       Exit
    }
}

In the above code, I added a simple if statement. It monitors whether or not the Help parameter is used when the function is invoked. If it is, it runs the Get-Help cmdlet against the name of the executing function—itself—using the $MyInvocation variable and then exits the function.

Clear-UserTemporaryFile -Help
NAME
    Clear-UserTemporaryFile

SYNOPSIS
    The Clear-UserTemporaryFile command ...

SYNTAX
    Clear-UserTemporaryFile [-ALL] [[-TIF] <String>] [[-TMP] <String>] [[-SIZE] <String>] [-HELP] [<CommonParameters>]

DESCRIPTION

RELATED LINKS

REMARKS
    To see the examples, type: "Get-Help Clear-UserTemporaryFile -Examples"
    For more information, type: "Get-Help Clear-UserTemporaryFile -Detailed"
    For technical information, type: "Get-Help Clear-UserTemporaryFile -Full"

At this point, some of you may already know where I’m going to go next. There was something else I had forgotten about every cmdlet and function written. They all have something in common. And what’s that? There is a way to return a command’s help using, of all things, the question mark! Take a look using the built-in Get-Verb and Get-Command cmdlets below.

Get-Verb -?
NAME
    Get-Verb

SYNTAX
    Get-Verb [[-Verb] <string[]>] [[-Group] {Common | Communications | Data | Diagnostic | Lifecycle | Other |
    Security}] [<CommonParameters>]

ALIASES
    None

REMARKS
    Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
        -- To download and install Help files for the module that includes this cmdlet, use Update-Help.
        -- To view the Help topic for this cmdlet online, type: "Get-Help Get-Verb -Online" or
           go to https://go.microsoft.com/fwlink/?LinkID=2097026.
Get-Command -?
NAME
    Get-Command

SYNTAX
    Get-Command [[-ArgumentList] <Object[]>] [-Verb <string[]>] [-Noun <string[]>] [-Module <string[]>]
    [-FullyQualifiedModule <ModuleSpecification[]>] [-TotalCount <int>] [-Syntax] [-ShowCommandInfo] [-All]
    [-ListImported] [-ParameterName <string[]>] [-ParameterType <PSTypeName[]>] [<CommonParameters>]

    Get-Command [[-Name] <string[]>] [[-ArgumentList] <Object[]>] [-Module <string[]>] [-FullyQualifiedModule
    <ModuleSpecification[]>] [-CommandType {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script
    | Configuration | All}] [-TotalCount <int>] [-Syntax] [-ShowCommandInfo] [-All] [-ListImported] [-ParameterName
    <string[]>] [-ParameterType <PSTypeName[]>] [-UseFuzzyMatching] [-UseAbbreviationExpansion] [<CommonParameters>]

ALIASES
    gcm

REMARKS
    Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
        -- To download and install Help files for the module that includes this cmdlet, use Update-Help.
        -- To view the Help topic for this cmdlet online, type: "Get-Help Get-Command -Online" or
           go to https://go.microsoft.com/fwlink/?LinkID=2096579.

This means I don’t even need a Help parameter. PowerShell already has this covered, and here’s the proof.

Clear-UserTemporaryFile -?
NAME
    Clear-UserTemporaryFile

SYNOPSIS
    The Clear-UserTemporaryFile command ...

SYNTAX
    Clear-UserTemporaryFile [-ALL] [[-TIF] <String>] [[-TMP] <String>] [[-SIZE] <String>] [-HELP] [<CommonParameters>]

DESCRIPTION

RELATED LINKS

REMARKS
    To see the examples, type: "Get-Help Clear-UserTemporaryFile -Examples"
    For more information, type: "Get-Help Clear-UserTemporaryFile -Detailed"
    For technical information, type: "Get-Help Clear-UserTemporaryFile -Full"

Edit: We know that we were able to use this PowerShell to return the help for our function,

Get-Help -Name "$($MyInvocation.MyCommand.Name)"

but we could’ve just as easily done this:

Invoke-Expression -Command "$($MyInvocation.MyCommand.Name) -?"

The first option invokes the Get-Help cmdlet against our function. The second option invokes the same function that’s already being invoked, adding a -? to the end of the complete command.

Write-Output Gets Foreground and Background Colors and More

Every once in a while a forum post comes along that really captures my interest. Take this one for instance.

In this post, the creator wanted to build out a start up menu in the ConsoleHost that has a solid white line, another white line below that, with the words “PowerShell Project 1” in it, and a final white line beneath that. That might be difficult to imagine, so here’s a visual representation, and then what his/hers looked like. I had recommended to use a here-string to fix the problem, but unfortunately we didn’t have the same results.

write-output-gets-foreground-and-background-colors-and-more01
Note: While you can’t see them, in both this and the below image, there are spaces on the lines above, below, and before and after “PowerShell Project 1.” This is how we can ensure the white rectangle around the text.

write-output-gets-foreground-and-background-colors-and-more02

I can’t say for certain why theirs rendered differently, but I suspect version, or PSReadline, or possibly console font/size. That wasn’t important; what was, was trying to figure out a way around this problematic inconsistency. We have the option to change the background color of the area where we type, and so I wondered if I could temporarily do that inside the ConsoleHost. It turns out I could. With that new piece of knowledge, I set out to write a wrapper function around Write-Output. In my version — Write-TMOutput — it includes -ForegroundColor and -BackgroundColor parameters with an option to horizontally and vertically pad the text (object).

First, here’s a few images to show my new function in action. This first image shows the commands included in the TMOutput module.

write-output-gets-foreground-and-background-colors-and-more03

The next example image shows some basic, Write-Output type usage. One where we pipe to the function, and one where we don’t. Fairly standard.

write-output-gets-foreground-and-background-colors-and-more04

Now, the next example is where this starts to get fun: the incorporation of the -ForegroundColor and -BackgroundColor parameters. Prior to running these commands, and those in the last two examples, I removed the PSReadLine module so the colors would be easier to spot.

write-output-gets-foreground-and-background-colors-and-more05

Next is a demo of two additional parameters: -HorizontalPad and -VerticalPad. These will allow you to add spaces before and after the value supplied to the -InputObject parameter (the text), and add lines above and below the text. This is the part that gets back to the request in the Microsoft Technet forum post. I should mention that my solution in the forum post would be different now that I’ve spend some time writing this function — there are better ways to do things that I hadn’t considered at the time I replied to the post.

write-output-gets-foreground-and-background-colors-and-more06

The next example shows some usage with the Get-ADUser cmdlet. Keep in mind that if you combine this function with other cmdlets, that the -HorizontalPad and -VerticalPad parameters cannot be used. In my mind, they’re just a bonus to the option of using colors with Write-Output. I should mention it now, but this function was intentionally written to only work in the ConsoleHost. Perhaps I’ll add the option of using it in the ISE in the future.

write-output-gets-foreground-and-background-colors-and-more07

I’ve written an additional function that will allow you to quickly see the available colors from which you can choose. It’s called Show-TMOutputColor, and produces the results below. This might come in handy as you’re using the modified Write-Output.

write-output-gets-foreground-and-background-colors-and-more08

Now, on to the module. It’s the first time I’ve done it, but I’ve uploaded this to the PowerShell Gallery. I believe publishing to the PowerShell Gallery was one of my PowerShell New Year’s Resolutions for 2016, so there’s one down! You can use this direct link or, one better, download the module from your console, using this command:

Install-Module -Name TMOutput

Thanks for reading this post. Hopefully these function will be a useful way to get around the need for Write-Host’s foreground and background color options while working in the console. That, and maybe the TechNet thread creator can do whatever they wanted, too.

Get Active Directory (Sites and Services) Subnets

I just started reading chapter 16 — Managing sites and subnets — in Richard Siddaway‘s book Learn Active Directory in a Month of Lunches. I already know a good deal about Active Directory (AD). I’ve been using and supporting it, in one fashion or another, since its introduction in 2000. Even so, that didn’t stop me from picking up this title. I’ll buy and read a book about a topic I already know, even if I’m only going to pick up a few new details. I also like to remind myself of things I already know, in an effort to keep things as fresh as possible in my mind. I’ve also found myself curious about other people’s writing styles. Since I’ve been writing and posting here, for coming up on a year and a half, I believe that my writing has improved, and it makes me eager to read other people’s writings, too.

I went a little off topic there, but anyway, I read a couple pages of the chapter, and then typed the command below into my Windows PowerShell console. This was in an effort to determine the subnets used by an AD site, before reading any further.

PS> (Get-ADReplicationSite -Identity Downtown02 -Properties Subnets).Subnets.ForEach{$_.Split(',',2)[0].Split('=')[-1]}
10.115.0.0/16
10.122.0.0/15
10.140.0.0/16

So what’s happening here? By default, the Active Directory Get-ADReplicationSite cmdlet returns information about your (computer’s) AD site; however, you can filter the results to get information about another AD site, or even, all the AD sites. In my example, I’ve indicated that I only want information about a single site, Downtown02. Although you don’t see it in the default properties that are returned by this cmdlet, there are extended properties returned when the -Properties parameter is included. This behavior is similar to some of the other AD cmdlets. In fact, you can see which AD cmdlets have a -Properties parameter by enter this: Get-Command -Module ActiveDirectory -ParameterName Properties. In our example, we are only returning the Subnets property, not all of the properties, as we would when using -Properties *.

The Subnet property is returned as a Distinguished Name, such as: CN=10.115.0.0/16,CN=Subnets,CN=Sites,CN=Configuration,DC=mydomain,DC=com. Due to this, I’ve added the .Split() method, twice. The first time it was used, we split at the comma and returned two pieces of our string, when it’s entered as .Split(‘,’,2). That’s difficult to explain, so here’s what that looks like:

PS> (Get-ADReplicationSite -Identity Downtown02 -Properties Subnets).Subnets.ForEach{$_.Split(',',2)}
CN=10.115.0.0/16
CN=Subnets,CN=Sites,CN=Configuration,DC=catnet,DC=mydomain,DC=com
CN=10.122.0.0/15
CN=Subnets,CN=Sites,CN=Configuration,DC=catnet,DC=mydomain,DC=com
CN=10.140.0.0/16
CN=Subnets,CN=Sites,CN=Configuration,DC=catnet,DC=mydomain,DC=com

In the example above, notice it only split at the first comma in the string. That’s what the 2 does (“leave me 2 sections”). Adding the [0] index, below, only keeps the first element of the results of each split.

PS> (Get-ADReplicationSite -Identity Downtown02 -Properties Subnets).Subnets.ForEach{$_.Split(',',2)[0]}
CN=10.115.0.0/16
CN=10.122.0.0/15
CN=10.140.0.0/16

The second time we use the .Split() method, we split at the equal sign and return the last element, like so: .Split(‘=’)[-1]. After these two .Split() methods have run, we have our subnets, just like we’d see them in the Name category, of the Active Directory Sites and Services MMC. I should mention the syntax in this command. Take a closer look, if you haven’t already: It’s using the ForEach method, not the ForEach-Object cmdlet, as you might have expected to see. This syntax became possible in PowerShell 4.0.

Okay, so I’ve mentioned this a time or two, now. I often learn something new, share it here, and then I find a better way. Sometime, while I’m still writing. Well, that happened again. We don’t need to get fancy with the results of Get-ADReplicationSite as we have above, and can instead, use the Get-ADReplicationSubnet cmdlet. How’d I find the cmdlet? Well, (while writing), I decided to search for the string “subnet” in all the cmdlet names from the ActiveDirectory module: Get-Command -Module ActiveDirectory -Name *subnet*. Here’s the command to use to return the same information we did with the first example in this post.

PS> (Get-ADReplicationSubnet -Filter * -Properties Site | Where-Object Site -like '*Downtown02*').Name
10.115.0.0/16
10.122.0.0/15
10.140.0.0/16

If you’re wondering why I didn’t use the -Filter parameter to filter on the site, well then, here you go. Here’s a quicker and more efficient method in which to write the command.

PS> (Get-ADReplicationSubnet -Filter {Site -eq 'Downtown02'}).Name
10.115.0.0/16
10.122.0.0/15
10.140.0.0/16

Thanks for joining me, and now back to my reading.

Get Some Help for Later Reading

I’m just starting to get my hands wet with Microsoft Lync. As I often do, I use the Windows PowerShell cmdlets to help learn more about a product; I did this same thing with Hyper-V. The unfortunate thing about the GUI (think, an MMC snap-in for instance), is that the menu options don’t always tell you exactly what that option is going to do, or its exact purpose. While the GUI can be unclear, PowerShell tells you exactly what a cmdlet does. With that knowledge, I’ve often been able to relate a cmdlet, and its purpose, to its respective menu option in the GUI.

I wanted to read though the Lync cmdlet’s help files, but only the cmdlet name and its synopsis. Here’s the command I ran to extract this information for later reading.

PS C:> Get-Command -Module Lync | Get-Help | Select-Object Name,Synopsis | Export-Csv -Path C:\LyncCmdlets.csv -NoTypeInfomation

The command above works this way: it returns all the cmdlets included in the Lync Module and sends (pipes) those to the Get-Help cmdlet. The Get-Help cmdlet pipes its results to Select-Object which filters the returned properties to just the Name and Synopsis from each cmdlet’s help file. At the end, those filtered results are sent to Export-Csv which creates a file I can read at my leisure.

Although there’s over 500 cmdlets, it’s safe to say that many of the nouns (the part after the dash [-]) will be the same across some of the cmdlets. That means that many of the Get-* cmdlets will have a partnering Set-* cmdlet. Get reads information and Set changes it. These nouns may also have a matching New-*, Remove-*, and possibly even a Test-* cmdlet. Now off to do some reading…

Creating Multiple Credential Objects

Download the complete function: https://gist.github.com/tommymaynard/98031ccd5de67005bf3063db06a33851

There are times when you made need to use additional credentials, other than those used to begin the Windows PowerShell session. When I need to PSRemote to another domain’s computer, I quickly run a function I have stored in my $PROFILE to create a variable that contains a credential object for the second domain. It’s a bit more specific for my environment, so I won’t bother sharing that exact function. What I will do, however, is share and explain a function I’ve written to create up to 10 credential objects. You’ll soon see where that can be changed (if for some reason someone would want more than that many). Realistically, 10 seems much too high anyway. Moving on.

Now, it might be important to know a bit more about how this started. The unfortunate thing about that function (the one in the link) is that it is maxed out at three credential sets (and it continually used the word ‘domain’). As well, it wasn’t as flexible as it should’ve been and it didn’t have any comment-based help or any verbose statements. So, a couple of days after publishing that post, I copied the function back into the PowerShell ISE and started working on a “1.1” version. That’s what we’ll discuss in this post.

First, we’ll write some basic, structural code for the advanced function.

Function New-TMMultiCred {
    [CmdletBinding()]
    Param ()

    Begin {
    } #End Begin

    Process {
    } #End Begin
} #End Function

Now, let’s add the parameter that will define how many credential objects the function will create. The variable we’ll use is $Set and we’ll cast it as an integer (Set will, therefore, also be the name of the parameter). In addition, we’ll add code to define the -Set parameter as being mandatory (it must be included when the function is run), and make the parameter positional (the value for -Set can be entered without providing the -Set parameter name). In addition, we’ll add the ValidateRange validation attribute that will require that the integer entered, as the value for the -Set parameter, must be 1 through 10. This can be changed if necessary.

Function New-TMMultiCred {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$True,Position=0)]
        [ValidateRange(1,10)]
        [int]$Set
    )

    Begin {
    } #End Begin

    Process {
    } #End Begin
} #End Function

We won’t need to do anything in the Begin block, so we’ll focus on the Process block next. In there, we’ll need to prompt for a user name and password as many times as the value of the parameter -Set indicates. Since we know the number of times we’ll be looping (to prompt for the username and password), I recommend we use a for statement. For statements work this way: set a variable ($i in our case) as a counter variable, add a comparison to determine how many times to loop (while $i is less than or equal to $Set), and finally, include a way to increment the counter variable (that’s what $i++ does), so that we only loop the proper number of times.

Function New-TMMultiCred {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$True,Position=0)]
        [ValidateRange(1,10)]
        [int]$Set
    )

    Begin {
    } #End Begin

    Process {
        For ($i = 1; $i -le $Set; $i++) {

        }
    } #End Begin
} #End Function

The final piece is adding the parts necessary to prompt for usernames and passwords, and creating variables to store each of the credential objects. We’ll do this as part of a try-catch.

Line 15 below, first runs the Get-Credential cmdlet. We know this because it is in parenthesis. These parentheses indicate that this cmdlet needs to run before it’s used as the value of the Set-Variable‘s -Value parameter. If for some reason the user presses Cancel, or presses the X in the top-right corner of the prompt dialog, the try portion of the try-catch will fail, and the catch portion will run. It will indicate that no credential was created for that iteration through the loop.

If the user enters, at minimum a username (because a password can be blank), then it will set a variable called $CredSet# (the hash mark (#) indicates a number). If we indicate we want to create two credential objects when we run the function (New-TMMultiCred 2), then $CredSet1 will be the variable that holds the first credential object, and $CredSet2 will hold the second.

Still on line 15, notice that the -Scope parameter is being used with the Set-Variable cmdlet. If we didn’t include this parameter and its value, Global, then the variables created (or modified, if the variable(s) already existed) by this command would not be available after the function was done executing.

Function New-TMMultiCred {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$True,Position=0)]
        [ValidateRange(1,10)]
        [int]$Set
    )

    Begin {
    } #End Begin

    Process {
        For ($i = 1; $i -le $Set; $i++) {
            try {
                Set-Variable -Name CredSet$($i) -Value (Get-Credential -Credential $null) -Scope Global
                Write-Output -Verbose "SUCCESS: Credential Set $i stored in `$CredSet$($i)"
            } catch {
                Write-Warning -Verbose "No credential object was created for set $($i)."
            }
        }
    } #End Begin
} #End Function

Here’s a look at the function in progress. The first image shows that three credential objects were requested. The first credential object has already been created and is stored in $CredSet1, the second wasn’t created, since the user pressed Cancel on the second prompt, and the third credential object will be created when the user presses OK. The second image shows the end result.

Function for Creating Multiple Credential Objects-01

Function for Creating Multiple Credential Objects-02

Once this is complete, the user can run cmdlets that have an optional -Credential parameter and supply the fitting credential object, as seen in the example below. You can return all the cmdlets and functions that have the -Credential parameter using Get-Command: Get-Command -ParameterName Credential.

PS C:\> Invoke-Command -ComputerName dc01 -ScriptBlock {Get-Date} -Credential $CredSet3

Download the complete function: https://gist.github.com/tommymaynard/98031ccd5de67005bf3063db06a33851

Cmdlets of the Same Name (VMware & Hyper-V)

Update: This post was submitted to PowerShell.org for their PowerShell TechLetter. For the most update to date version of this post, please read it here: http://powershell.org/techletter/issues/2015-01-january.php#Article1

One of the first things I did when I moved to Windows 8.1 (and Windows PowerShell 4.0, by default), was to add the Hyper-V feature. If you didn’t already know, yes, you can run virtual machines in Windows 8.1 without the need for third-party software. I can’t be 100% certain, but I’m fairly certain I installed this feature a year ago on Windows 8, as well. In both operating systems, you will need to meet some hardware requirements to install Hyper-V, otherwise the feature will be grayed out. In addition, it may not even be listed in non-Pro and non-Enterprise versions of Windows 8.1.

Adding Hyper-V was twofold. One, I wanted to gain experience with the Hyper-V cmdlets and two, I wanted to add at least a couple virtual machines to my computer – Windows 8.1 to test PowerShell 5.0, and Windows 7 with PowerShell 3.0. After a day or so of playing with Hyper-V, it occurred to me that my future work with PowerCLI, VMware’s vSphere PowerShell PSSnapin, meant there would be name overlap between cmdlets in Hyper-V and cmdlets in VMware. This includes popular cmdlets, such as Get-VM and Get-VMHost.

In previous experience, I had learned about command precedence (Get-Help about_Command_Precedence). These are the precedence rules that are used when a command runs. If we have an alias, a function, a cmdlet, and a native Windows command, all with the same name, it will run the alias first when the name is entered into the PowerShell console. If we don’t have an alias with that name, but do have a function, a cmdlet, and native Windows command, then it will run the function. If the name is the same, but the command type is different, then they will always run in order from alias to function to cmdlet to native Windows command.

If we have two of the same command type and they have the same name, such as the cmdlet Get-VM, it will run the one that was added most recently. This is unless we provide the cmdlet a path. For instance, if the Hyper-V module was loaded and then the VMware PSSnapin was loaded, when we run Get-VM it will run the cmdlet from VMware. If we wanted to use the Get-VM cmdlet from the Hyper-V module, we would need to enter the full path that includes the module name: Hyper-V\Get-VM. Just because one cmdlet was loaded more recently, doesn’t mean the other one is gone.

In my mind, there’s a couple ways to fix the problem, or rather, make it easier to use cmdlets with the same name. The first option I tried, was to determine if the Add-PSSnapin cmdlet, that is used by VMware, had a -Prefix parameter. It didn’t, but had it, I could have added a prefix to all the VMware cmdlets with an option like the example below.

Add-PSSnapin -Name VMware.VimAutomation.Core -Prefix VMware

This doesn’t actually work. Read the post.

An option like this wouldn’t have clobbered my Hyper-V cmdlets, and therefore, Hyper-V’s Get-VM cmdlet would still work without a path, and VMware’s Get-VM cmdlet, for example, would have been Get-VMwareVM. The Import-Module cmdlet does have a -Prefix parameter so I could have changed the Hyper-V cmdlets to use a prefix, but I didn’t think the Hyper-V cmdlets should be the ones to suffer. I’m a PowerShell enthusiast, and I didn’t want to change the naming of Microsoft-built cmdlets, and therefore, learn them incorrectly.

Here’s what I did. I added a function to my profile ($PROFILE) that would allow me to choose which set of cmdlets would be loaded first, and which would be loaded second. The cmdlets I loaded second wouldn’t need the path to use them. This meant I could set the Hyper-V cmdlets to not need a path when I work with those, or I could set VMware cmdlets to not need a path when I work with those.

I started by declaring an empty function called Add-VMCs (Virtual Machine Cmdlets) that included a single parameter called Default.

Function Add-VMCs($Default) {

}

I started the function with an If statement. On line 2, below, it checks the parameter that has been provided when calling the function. If it matches the letter h or the letter v it will continue to line 3. If it does not, it will jump to line 7 and run the Else portion – displaying a message that nothing was changed and what parameters can be used. Line 3 and 4 remove the Hyper-V module and VMware PSSnapin, whether or not they are already loaded. While there could have been some logic to first check if they are loaded, I decided I was fine with hiding any errors that might occur (-ErrorAction SilentlyContinue) if I tried to unload a module or PSSnapin that wasn’t already loaded. I usually handle errors better than this, but I didn’t think it was necessary for this function.

The reason this is required is because if we try to load an already loaded module or PSSnapin, it won’t actually bother doing it, or at least that’s what I think is going on. This would prevent the function from ensuring the module and PSSnapin were loaded in my preferred order. Remember, if cmdlet names are the same, the most recently loaded cmdlet will be the one that is used.

Function Add-VMCs($Default) {
    If ($Default -eq 'h' -or $Default -eq 'v') {
        Remove-Module -Name Hyper-V -ErrorAction SilentlyContinue
        Remove-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue

    } Else {
        Write-Output -Verbose "INFO: No changes made`r`nUse H to set Hyper-V as the default (Add-VMCs H) or use V to set VMware as the default (Add-VMCs V)."
    }
 }

Like we said previously, if the parameter is equal to the letter v or the letter h, it will remove the module and PSSnapin. The function continues to an If-ElseIf statement that begins on line 5. This bit of logic takes different actions depending on the value of the parameter. If the parameter is equal to the letter h, it will load the VMware PSSnapin and then import the Hyper-V module. This means that Get-VM would be the cmdlet associated with Hyper-V. If it is not equal to the letter h, and instead it is equal to the letter v, then it will load the Hyper-V module and then the VMware PSSnapin. This means that Get-VM would be the cmdlet associated with VMware.

Function Add-VMCs($Default) {
    If ($Default -eq 'h' -or $Default -eq 'v') {
        Remove-Module -Name Hyper-V -ErrorAction SilentlyContinue
        Remove-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue
        If ($Default -eq 'h') {
            Add-PSSnapin -Name VMware.VimAutomation.Core
            Import-Module -Name Hyper-V
        } ElseIf ($Default -eq 'v') {
            Import-Module -Name Hyper-V
            Add-PSSnapin -Name VMware.VimAutomation.Core
        }
    } Else {
        Write-Output -Verbose "INFO: No changes made`r`nUse H to set Hyper-V as the default (Add-VMCs H) or use V to set VMware as the default (Add-VMCs V)."
    }
}

Here’s the function in action. At first I set the Hyper-V cmdlets to be the default on line 1. I then verify that my cmdlet is from the correct module by using the Get-Command cmdlet. Once that’s been verified, I run the Get-VM cmdlet on line 8. Then, I do it all again after I change the default to VMware. Note: If you’ve ever used VMware’s PowerCLI then you know I had to use the Connect-VIServer cmdlet to connect to a vCenter system before it would allow me to run the VMWare Get-VM cmdlet.

PS C:\> Add-VMCs -Default H
PS C:\> Get-Command Get-VM

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Cmdlet          Get-VM                                             Hyper-V

PS C:\> Get-VM -Name Win8.1*

Name        State   CPUUsage(%) MemoryAssigned(M) Uptime   Status
----        -----   ----------- ----------------- ------   ------
Win8.1PS5.0 Running 23          1536              00:26:20 Operating normally

PS C:\> Add-VMCs V
PS C:\> Get-Command Get-VM

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Cmdlet          Get-VM                                             VMware.VimAutomation.Core

PS C:\> Get-VM -Name Windows*

Name                 PowerState Num CPUs MemoryGB
----                 ---------- -------- --------
Windows 2003 R2 S... PoweredOff 1        1.000

Linked from here:
http://blogs.technet.com/b/heyscriptingguy/archive/2014/09/04/powertip-use-complete-name-for-powershell-cmdlet.aspx