Reader small image

You're reading from  Mastering PowerCLI

Product typeBook
Published inOct 2015
Reading LevelIntermediate
PublisherPackt
ISBN-139781785286858
Edition1st Edition
Languages
Right arrow
Author (1)
Sajal Debnath
Sajal Debnath
author image
Sajal Debnath

Sajal Debnath is a highly certified Cloud computing technocrat with more than 12 years of experience in virtualized data center design, Cloud computing, and BC/DR solutions. He is an EMCISA, VCAP-DCD/DCA, VCAP-CID/CIA, RHCE 4/5/6, RHCVA, Openstack, and ITIL certified person. He is presently associated with VMware Software India Pvt. Ltd. as a senior system engineer. Previously, he worked with France Telecom, Hewlett Packard, and many more in multiple roles. He is involved in prestigious Indian government projects, such as National Cloud, Digital Locker, and so on.
Read more about Sajal Debnath

Right arrow

Chapter 2. Reusable Advanced Functions and Scripts

In the first chapter, we revisited PowerShell and PowerCLI basics. Then, we discussed how we could use the GitHub version to control our work and collaborate with others to work on the same project. We also learned how to use Pester to do unit testing on our work. In this chapter, we are going to cover advanced functions and their implementations in PowerShell. Specifically, we are going to talk about the following topics:

  • Specifying function attributes

  • Specifying parameter attributes

  • Using parameter validation attributes

  • Using dynamic parameters

  • PowerShell help files

  • Creating comment-based help

  • Error handling in PowerShell

Before we start discussing advanced functions, let's take a look at normal functions. If you type Get-Help About_Functions in PowerShell, you can get the details of functions. The description says a function is a list of Windows PowerShell statements that has a name that you can assign. When you run a function, you type the function...

Specifying function attributes


In case of advanced functions, we use Cmdlet bindings to control the feature or function of the function itself. With this, we define how the function works or behaves.

Addition of the [CmdletBinding()]line allows you to define these controls in an advanced function. Note that with the use of CmdletBinding(), we get the $PSCmdlet automatic variable, but the $Args variable is not available in these functions.

In advanced functions, with the CmdletBinding attribute, unknown parameters and positional arguments that do not have any matching positional parameters results in parameter binding to fail.

Let's examine the available options with the CmdletBinding() attribute and their meaning:

<#
     Comment Based Help
#>
function <function_name> {

[CmdletBinding(ConfirmImpact=<String>,
                     DefaultParameterSetName=<String>,
                     HelpURI=<URI>,
                     SupportsPaging=<Boolean>,
          ...

Specifying parameter attributes


In this section, we will discuss the parameter attributes and how to set them. The attributes falling under this category define the different attributes of the parameter itself. Let's take a closer look at the most useful and common options available to define parameter attributes and their uses:

  • Mandatory argument: This argument indicates that this particular parameter is compulsory, otherwise it is optional. For example, if I am writing a function to connect to a vCenter server and doing some work and I want the vCenter name to be provided at runtime, then the following code makes sure that the cmdlet call will fail without the $VCName parameter:

    Param (
      [parameter(Mandatory=$true)]
      [String]$VCName
    )
  • Position argument: We define the positional argument to specify which value will be assigned to which parameter by the position of the values at runtime, without the need to specify the parameter name. PowerShell will understand which parameter the value...

Using parameter validation attributes


Attributes falling under this category define the attributes that we can use to validate the value of a parameter/variable itself. The following is a list of the most commonly used parameters:

  • AllowNull / AllowEmptyString: This attribute allows a mandatory parameter to accept a NULL value or empty string. Check the following example. When this attribute is not set, the function does not allow us to give an empty string as an input to the $VCName parameter, as it is a mandatory input. When we comment out the AllowEmptyString parameter, it throws an error:

    Function Get-VC{
        [cmdletbinding()]
    
        Param(
        [Parameter(Mandatory = $true)]
    #    [AllowEmptyString()]
        [String]$VCName
        )
        Write-Host "vCenter Name: $VCName"
    }

    Notice that, when this attribute is set, the function allows us to give an empty string as the input to the $VCName parameter:

  • ValidateCount: This attribute specifies the minimum and maximum number of values that a parameter accepts...

Dynamic parameters


All the earlier examples were examples of static parameters. Before the cmdlets of the function are executed, these parameters come into existence and remain available for the entire duration of the scope of the function. Dynamic parameters are those parameters that are defined in such a way that depending on certain conditions only, they come into existence. It may be designed in such a way that a dynamic parameter will come into existence only when another parameter is used in the function or a parameter has a certain value. So, late binding is applied for these types of parameters.

For example, let's discuss the following requirements:

  • We want to create a VM, provided the VM name is given by a user.

  • We have three different environments named Dedicated, Shared, and Cloud where the VM can be created.

  • If any environment is not mentioned by a user, then by default the VM will be created in the shared environment.

  • For a shared and Cloud environment, providing a VM name would...

Switch parameters


Switch parameters are parameters without any need to assign any value to them. As the name suggests, they act as a switch. By default, their values are $false. Once these parameters are mentioned in the command line, their values become $true. We can use this switch parameter to perform our checks and run their respective script blocks. The following example is a function that connects to a vCenter server or vCloud Director server based on the input that we provide. As parameter values, we accept ServerName and UserName to connect to the server, Password for the connection, and another parameter that will act as a switch. If we mention –VCServer in the command line, then the Connect-VIServer cmdlets will be executed; if –VCDServer is mentioned, then the Connect-CIServer cmdlets will be executed. So, run the following code snippet:

Function Connect-Server{
[CmdletBinding()]
 Param(
    [Parameter(Mandatory=$true)]
            [string]$ServerName,
            [string]$UserName...

PowerShell help files


Help files are the best way to get help (pun intended) in PowerShell. They provide the most intensive details about the cmdlet and includes overviews, detailed explanations, examples, and much more. As its name suggests, you get help by running the Get-Help cmdlet.

For people out there who love *NIX, Get-Help is the equivalent of man pages in the Linux or Unix environment. Actually, an alias of man à Get-Help exists in PowerShell (thanks to Brian Wuchner for pointing this out).

The first thing that you notice in PowerShell 3.0 onward is that all the help files are not included as part of the package itself. In order to use the full range and the updated help files, you need to get them from the Microsoft website. If you try to use Get-Help for a cmdlet for which the help files are not downloaded yet, you get a short help description and then the following notification:

So, you need to run Update-Help to update all the help files. What this command does is that it checks...

Creating comment-based help


Comment-based help is the easiest way to create help for the scripts that you write. If you write comment-based help in your function, then the Get-Help cmdlet will show you help for the function in the same way as it shows the help for any other PowerShell native cmdlet. So, whenever you are writing an advanced function, you should include comment-based help so that end users can utilize the help of the Get-help cmdlet to work with the function.

Before we go ahead and dive into comment-based help, I would like to draw your attention to the following fact.

You have just seen the preceding function where I created a dynamic variable to accept the user id, vmName, and environment where I can create VMs. Note that, in this function, I did not write any help, so what happens if I try to run Get-Help on this function? Let's see.

Wow! It gives a short description. Let's try the –Full version.

Pretty amazing right? It provides help in the same format as it provides for other...

Error handling in PowerShell


Before we go ahead and talk about how to handle errors or avoid them while writing scripts in PowerShell, let's speak about a few of the inherent features of advanced functions that can help end users. These are Write-Verbose, Write-Error, Write-Warning, and –Whatif. These are not typical error handling ways in PowerShell, but by using these in advanced functions, you can provide more ways to avoid errors in scripts.

Write-Verbose allows you to define more information for end users when they run the script/function/cmdlet with the –Verbose option. The same goes for the Write-Error and Write-Warning options. Defining –Whatif would allow end users to know what exactly the script will do if it is run normally. The following is a sample script showing all of these:

–WhatIf will only show the purpose of the script. If more than two VMnames are provided, then there will be an error message shown but not providing any VM name will result in an error. The following is...

Summary


In this chapter, we covered advanced functions, how to write them, and details of different attributes. Next, we learned about help files in PowerShell and how we can write our own help files using comment-based help. At the end, we learned how we can use different methods of error handling in PowerShell or how we can troubleshoot scripts. Although we did not cover all aspects of these topics, we did cover those topics required for advanced script writing.

In the next chapter, we will dive into PowerCLI and cover how to build ESXi images using Image Builder. Next, we will cover how to auto deploy an ESXI host, add a host to a vCenter server, and how to use host profiles in the ESXi environment using PowerCLI.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering PowerCLI
Published in: Oct 2015Publisher: PacktISBN-13: 9781785286858
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Sajal Debnath

Sajal Debnath is a highly certified Cloud computing technocrat with more than 12 years of experience in virtualized data center design, Cloud computing, and BC/DR solutions. He is an EMCISA, VCAP-DCD/DCA, VCAP-CID/CIA, RHCE 4/5/6, RHCVA, Openstack, and ITIL certified person. He is presently associated with VMware Software India Pvt. Ltd. as a senior system engineer. Previously, he worked with France Telecom, Hewlett Packard, and many more in multiple roles. He is involved in prestigious Indian government projects, such as National Cloud, Digital Locker, and so on.
Read more about Sajal Debnath