Handling lots of parameters

The Scripting Games practice event for this season evokes scripts that have a lot of switch parameters.

I saw lots of stacks of IF statements among the entries dealing with those switches.

When I see stacks of IF statements I have to wonder if might not be better to have a Switch instead.

After tinkering at it a while, with the intent of producing something that was relatively easy to maintain (after you put it into production, somebody is going to want stuff added to it, trust me on this) I have this:


function Get-Inventory
{
[cmdletbinding()]

param (
[String[]]$ComputerName,
[Switch]$Hardware,
[Switch]$LastPatch,
[Switch]$Roles,
[Switch]$Components,
[Switch]$AllReports
)

End {

foreach ($ComputerName in $ComputerNames)
{
$PropHash = [ordered]@{}

Switch -Regex ($PSBoundParameters.GetEnumerator().
Where({$_.Value -eq $true}).Key)
{
'Hardware|AllReports' 
{ 'Manufacturer','Model','CPU','RAM','Disks' | Get-ReportProp }

'LastPatch|AllReports' 
{ 'LastPatch','LastReboot' | Get-ReportProp }

'Roles|AllReports' 
{ 'ServerRoles'| Get-ReportProp }

'Components|AllReports'
{ 'Components' | Get-ReportProp }

} #End Switch

[PSCustomObject]$PropHash

} #End ForEach

} #End End Block


Begin{

[Array]$ComputerNames = $ComputerName

function Get-Manufacturer {}
function Get-Model {}
function Get-CPU {}
function Get-Disks {}
function Get-LastPatch {}
function Get-LastReboot {}
function Get-ServerRoles {}
function Get-Components {}

filter Get-ReportProp { $PropHash[$_] = Invoke-Expression "Get-$_ $ComputerName" }

} #End Begin block

Process { $ComputerNames += $_ } #Process Block

}#End Get-Inventory Function

Advertisements

2 responses to “Handling lots of parameters

  1. Jeffrey Snover [MSFT]

    Cool approach!

    Jeffrey Snover[MSFT]
    Distinguished Engineer and Lead Architect for Windows Server and System Center

  2. Nice work! learned something today šŸ™‚

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s