Created
February 23, 2014 06:26
-
-
Save kdoblosky/9167856 to your computer and use it in GitHub Desktop.
Creating objects with methods in PowerShell - Part 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Code from my blog entry at http://betterlivingthroughcode.blogspot.com/2014/02/creating-real-objects-in-powershell.html | |
$myObject = New-Object -TypeName PSObject | |
$myObject | Add-Member -MemberType NoteProperty -Name Name -Value "Kevin" | |
$myObject.Name | |
# Let's add a simple method | |
$myObject | Add-Member -MemberType ScriptMethod -Name SayHello -Value {"Hello $($this.Name)"} | |
$myObject.SayHello() | |
# Let's add a method with a parameter | |
$myObject | Add-Member -MemberType ScriptMethod -Name Say -Value {param($Message) "$Message $($this.Name)"} | |
$myObject.Say("What's up") | |
# That's missing a question mark at the end. Let's add an optional second parameter | |
$myObject | Add-Member -MemberType ScriptMethod -Name Say2 -Value {param($Message, $End) "$Message $($this.Name)$End"} | |
$myObject.Say2("What's up", "?") | |
# Let's put some constraints on what $Message can be | |
$myObject | Add-Member -MemberType ScriptMethod -Name Say3 -Value {param([ValidateSet("Hello", "Goodbye")]$Message, $End="") "$Message $($this.Name)$End"} | |
# Note we don't have to specify the second parameter, since we gave it a default value. | |
$myObject.Say3("Hello") | |
# Now let's try with an invalid value for $Message | |
$myObject.Say3("What's up", "?") | |
# Let's create a script block | |
$nameGame = { | |
$nameEnd = $this.Name.Substring(1) | |
"$($this.Name) $($this.Name) bo b$nameEnd" | |
"banana fana fo f$nameEnd" | |
"fee fi mo m$nameEnd" | |
"$($this.Name)" | |
} | |
# Then add it to our object | |
$myObject | Add-Member -MemberType ScriptMethod -Name PlayNameGame -Value $nameGame | |
$myObject.PlayNameGame() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment