Simply put, an advanced function acts very much like a standard cmdlet.
This allows me to create simple one-liners that will a) select the VMs I’d like to query and b) format the output however I would like. Unlike having to create a new full script each time you want to accomplish a task, an advanced function is flexible, versatile and possibly most importantly – easily reusable. This makes them ideal for inclusion into modules that load any time you fire up PowerShell.
Below is the code for the (simple) advanced function I created – Get-VMInfo. As you can see the code is pretty simple though it makes for a great example. You feed it a list of VMs via the pipeline and it returns the info you requested via custom objects. Let’s see how we could utilize the function assuming we are connected to vCenter and have PowerCLI loaded.
Gather a list of all VMs and pipe to Get-VMInfo
Get-VM | Get-VMInfo
Gather a list of VMs in a particular cluster and pipe to Get-VMInfo
Get-Cluster MyCluster | Get-VM | Get-VMInfo
Gather a list of VMs in a particular vSphere folder and pipe to Get-VMInfo
Get-Folder Servers | Get-VM | Get-VMInfo
Now lets do something more with the output.
Gather a list of all VMs, pipe to Get-VMInfo then pipe to Export-Csv
Get-VM | Get-VMInfo | Export-Csv -NoTypeInformation -Path E:\VMInfo.csv
Gather a list of all VMs, pipe to Get-VMInfo, pipe to ConvertTo-HTML then pipe to Out-File
Get-VM | Get-VMInfo | ConvertTo-HTML | Out-File E:\VMInfo.html
As you can see, by using an advanced function I actually have more options available to me then if I had hard coded all these options into one mega script. It also saved me a lot of time.