WIDBA

WIDBA - The busiest DBA in Wisconsin, its all I do and I do it well

Wednesday, May 18, 2011

Powershell bondage, or at least binding.

I was out hunting around for best practices on writing Powershell commandlets and realized I was making one big mistake up front.  This article by Don Jones really explains the concept well.  I was really just writing functions, you don't have a commandlet until you have at least used cmdletbinding.  I think in the .Net world they call this "decorating" your function. 

For a straightforward example noting the two components in bold, when you use [CmdletBinding()] you can now use the -verbose switch, etc to add more value to your commandlets:

Function Get-CustomEventLog
{
  [CmdletBinding()]
  param([parameter(Mandatory=$true)][string]$computerName
              ,[string]$logName="Application", [string]$entryFilter="Error", [int]$rowsToReturn=25)

  Write-Verbose "Calling Get-EventLog for $computerName with $rowsToReturn rows"
  if($rowsToReturn -gt 100) {Write-Warning("Large Rowset potentially coming back");}
 
  Get-EventLog -ComputerName $computerName -LogName $logName -EntryType $entryFilter -Newest $rowsToReturn
}

Get-CustomEventLog -computerName "Consulting" -rowsToReturn 125 -verbose

No comments:

Post a Comment