Get-Beer Powershell function

Earlier in the week I had the privilege of presenting an introduction to Powershell/PowerCLI webex to a group of VMware customers. To help explain the Where-Object, Select-Object, and Sort-Object cmdlets, I thought it would be helpful to create a Get-Beer function. This function was a success, so I thought I would share it here. The function is very basic — it uses Import-CSV to read information from a file and returns the results ordered by name. The results can then be piped to other functions for demo purposes.

You can download a sample beer.csv file here.

Here is the function:


<#
.SYNOPSIS
List Miller Coors beer
.DESCRIPTION
This function returns a list of beer bottled by MillerCoors.
The object also includes nutrition and alcohol information.
.EXAMPLE
PS C:\> Get-Beer
.NOTES
This function was created for demo purposes only.  
VMware PowerCLI rocks!
#>
Function Get-Beer {
	$myResults = @()
	Import-Csv C:\tmp\beer.csv | Sort-Object Name | %{
		[decimal]$thisAlcoholPercent = $_."Alcohol%"
		[decimal]$thisCaloriesPer12oz = $_.CaloriesPer12oz
		$myResults += new-object -type PSObject -Property @{
			Name = $_.Name
			AlcoholPercent = $thisAlcoholPercent
			CaloriesPer12oz = $thisCaloriesPer12oz
			Category = $_.Category
		} #End New-Object
	} #End for each object
	
	# Return a custom PS object containing each beer
	return ($myResults | Select-Object Name, AlcoholPercent, CaloriesPer12oz, Category)
} #End Function

The function type casts the numeric values as decimal so that they properly sort. To run this, place a beer.csv file in the C:\tmp path (or adjust the filename/path in the function), paste the function into a powershell window and you are ready to go.

Here are a few examples of what you can do with this function:

Get-Beer

(Get-Beer).count

Get-Beer | Sort-Object AlcoholPercent -Descending | Select-Object Name, AlcoholPercent -First 5

Get-Beer | Where-Object {$_.CaloriesPer12oz -lt 200 -AND $_.Category -eq "Craft"} | Sort-Object AlcoholPercent -Descending | Select-Object -First 5
This entry was posted in Scripting. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *