Created
February 24, 2014 06:56
-
-
Save kdoblosky/9183113 to your computer and use it in GitHub Desktop.
Creating objects with methods in PowerShell - Part 2
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-objects-with-methods-in.html | |
$myObj1 = New-Object -TypeName PSObject -Property @{Prop1 = "1"; Prop2 = 2} | |
$myObj2 = [pscustomobject]@{Prop1 = "1"; Prop2 = 2} | |
$myObj2 | Get-Member | |
$myObj2.Prop1 = 42 | |
$myObj2 | Get-Member | |
$myObj3 = New-Module -ScriptBlock { | |
[string]$Prop1 = "1" | |
[int]$Prop2 = 2 | |
Export-ModuleMember -Function * -Variable * | |
} -AsCustomObject | |
$myObj3 | Get-Member | |
$myObj3.Prop2 = "Does this work?" | |
$myBook = New-Module -ScriptBlock { | |
[string]$Title = "" | |
[string]$Author = "" | |
[int]$NumberSold = 0 | |
[System.Nullable``1[[System.DateTime]]]$DatePublished = $null | |
Function WriteSummary() { | |
"$($this.Title) by $($this.Author), published on $(($this.DatePublished).ToString("yyyy-MM-dd")) has sold $($this.NumberSold) copies." | |
} | |
Export-ModuleMember -Function * -Variable * | |
} -AsCustomObject | |
$myBook.Author = "Robert Heinlein" | |
$myBook.Title = "The Moon is a Harsh Mistress" | |
$myBook.DatePublished = "1966-03-17" | |
$myBook.NumberSold = 1000000 | |
$myBook.WriteSummary() | |
Function New-Book { | |
param([string]$Title = "", [string]$Author = "", [int]$NumberSold = 0, [System.Nullable``1[[System.DateTime]]]$DatePublished = $null) | |
$newBook = New-Module -ScriptBlock { | |
[string]$Title = "" | |
[string]$Author = "" | |
[int]$NumberSold = 0 | |
[System.Nullable``1[[System.DateTime]]]$DatePublished = $null | |
Function WriteSummary() { | |
"$($this.Title) by $($this.Author), published on $(($this.DatePublished).ToString("yyyy-MM-dd")) has sold $($this.NumberSold) copies." | |
} | |
Export-ModuleMember -Function * -Variable * | |
} -AsCustomObject | |
$newBook.Author = $Author | |
$newBook.Title = $Title | |
$newBook.DatePublished = $DatePublished | |
$newBook.NumberSold = $NumberSold | |
$newBook | |
} | |
$jb = New-Book -Title "Jitterbug Perfume" -Author "Tom Robbins" -DatePublished "1984-09-07" -NumberSold 400000 | |
$hhgtg = New-Book -Title "The Hitchhiker's Guide to the Galaxy" -Author "Douglas Adams" -DatePublished "1979-10-12" -NumberSold 42 | |
$jb.WriteSummary() | |
$hhgtg.WriteSummary() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment