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
Cool approach!
Jeffrey Snover[MSFT]
Distinguished Engineer and Lead Architect for Windows Server and System Center
Nice work! learned something today š