Skip to content

Instantly share code, notes, and snippets.

@exospheredata
Created January 12, 2017 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exospheredata/70218b234c030c4b5f7eadb7e7a2d497 to your computer and use it in GitHub Desktop.
Save exospheredata/70218b234c030c4b5f7eadb7e7a2d497 to your computer and use it in GitHub Desktop.
Simple PowerShell v5 Class module to managing a ToyBox
#
# Example PowerShell v5 class for a ToyBox
#
# Jeremy Goodrum - ExosphereData, LLC 2017
# http://www.exospheredata.com/2017/01/12/building-your-first-powershell-class
enum EnumState
{
Missing
Stored
Playing
}
class ToyBox
{
# Name of the Toy or Item to be stored
[string] $Name
# Current State or Location of the Toy
[EnumState] $State
# This is currently a Favorited item or toy
[boolean] $Favorite
hidden [System.Object[]] $stored_Items
# New method to return all an object of Type [ToyBox] containing
# the currently declared object.
[ToyBox[]] Get()
{
return $this.GetMyItems()
}
[void] Save()
{
$this.SaveMyItems()
}
hidden [string[]] SaveMyItems ()
{
# Pull all of the stored_Items and return them for processing.
$___storedItems = $this.GetMyItems()
$__existingItem = $___storedItems | ?{$_.Name -eq $this.Name}
if (-not [string]::IsNullOrEmpty($__existingItem) ){
# If the item is already in the object, then we will want to
# update the values based on the current state
$__existingItem.Name = $this.Name
$__existingItem.State = $this.State
$__existingItem.Favorite = $this.Favorite
$__currentList = ($___storedItems | ?{$_.Name -ne $this.Name})
$__currentList += $__existingItem
$this.stored_Items = ($__currentList | ConvertTo-Json)
}
else{
# Since this item doesn't exist, we will just need to go ahead
# create it here. First, we will declare a hash of the object
# properties and then add it to our stored items. Finally,
# we will convert the entire thing into a JSON object to be stored
# in our hidden property.
$__newItem = @{
Name = $this.Name
State = $this.State
Favorite = $this.Favorite
}
$___storedItems += $__newItem
$this.stored_Items = ($___storedItems | ConvertTo-Json)
}
return $this.stored_Items
}
hidden [ToyBox[]] GetMyItems()
{
if (-not [string]::IsNullOrEmpty($this.stored_Items) ){
return ($this.stored_Items | ConvertFrom-Json)
} else {
return $null
}
}
static [ToyBox[]] op_Addition([ToyBox] $Left, [ToyBox] $Right)
{
$__current = @()
$__current += ($Left | ConvertTo-Json)
$__current += ($Right | ConvertTo-Json)
return ($__current | ConvertFrom-Json)
}
}
function New-ToyBox{
param(
[string] $Name,
[EnumState] $State,
[boolean] $Favorite
)
$__toyBox = [ToyBox]::new()
if($Name) {$__toyBox.Name = $Name}
if($State) {$__toyBox.State = $State}
if($Favorite) {$__toyBox.Favorite = $Favorite}
return $__toyBox
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment