Categories

Advanced Function update

If you were around PowerShell back in November 2007 you might remember that the PowerShell v2 CTP was the new kid in town. One of really big things at the time was script cmdlets – that we now call Advanced Functions.

Back in this post

http://richardspowershellblog.wordpress.com/2007/11/19/powershell-v2-script-cmdlets/

I showed how to write an Advanced Function / Script cmdlet / thingy

Having stumbled over the post today I thought I better bring it up to date so rewrote the code as a PowerShell v2 advanced function

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038

#Requires -Version 2
function write-myeventlog{ 
[CmdletBinding(SupportsShouldProcess=$true)] 
param ( 
[parameter(Position=0,
   Mandatory=$true,
   HelpMessage="Name of the event log to write to" )]
   [Alias("Name", "Log")]
 
  
[ValidateNotNullOrEmpty()]
   [string]$eventlogname,
 
  

[parameter(Position=1,
   HelpMessage="Message to write to event log" )]
   [Alias("msg")]
 
  
[ValidateNotNullOrEmpty()]
   [string]$Message,
 
   

[parameter(Position=2,
   HelpMessage="Type of event. Possible values are Error, Warning, Information, SuccessAudit, FailureAudit" )]
   [Alias("T")]
 
  
[ValidateNotNullOrEmpty()]
   [System.Diagnostics.EventLogEntryType]$Type

) 
BEGIN{}#begin
PROCESS{

$log = New-Object System.Diagnostics.EventLog
$log.set_log($EventLogName)
$log.set_source("PSscripts") 

if ($psCmdlet.ShouldProcess("$EventLogName", "Writing to"
)) {
   
$log.WriteEntry($Message,$Type
) 
}

}
#process
END{}#end
}

 

If you’ve looked at advanced functions this should be straight forward.

Define three parameters each of which is given a position. If the values are passed without the parameter name that is the order in which the data will be processed. Each parameter is given at least one alias and a help message. The value is also checked to make sure that it isn’t null or empty

The eventlog object is created and the message written. Because I used the [CmdletBinding()] attribute I can use –whatif as a parameter. The if statement allows the processing of -whatif

This code does exactly the same as the original but the syntax is up to date.

Not sure if the Write-Eventlog cmdlet was in the original CTP but don’t think it was which is why I used this example.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>