Created
July 14, 2017 11:08
-
-
Save OCram85/d673764614438493afaa5cd413999436 to your computer and use it in GitHub Desktop.
Powershell Classes - ReadOnly Properties
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
hidden AddPublicMember() { | |
$Members = $this | Get-Member -Force -MemberType Property -Name '_*' | |
ForEach ($Member in $Members) { | |
$PublicPropertyName = $Member.Name -replace '_', '' | |
# Define getter part | |
$Getter = "return `$this.{0}" -f $Member.Name | |
$Getter = [ScriptBlock]::Create($Getter) | |
# Define setter part | |
$Setter = "Write-Warning 'This is a readonly property.'" | |
$Setter = [ScriptBlock]::Create($Setter) | |
$AddMemberParams = @{ | |
Name = $PublicPropertyName | |
MemberType = 'ScriptProperty' | |
Value = $Getter | |
SecondValue = $Setter | |
} | |
$this | Add-Member @AddMemberParams | |
} | |
} |
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
Class DeathStar { | |
[String]$Class = 'Space battle station' | |
[Int]$Width = '160000' | |
[String[]]$HyperDriveRating = @('Class 4', 'Class 20') | |
$Crew = @{ | |
ImperialNavy = 342953 | |
Stormtroopers = 25984 | |
} | |
hidden [String]$_Ready = $null | |
hidden AddPublicMember() { | |
$Members = $this | Get-Member -Force -MemberType Property -Name '_*' | |
ForEach ($Member in $Members) { | |
$PublicPropertyName = $Member.Name -replace '_', '' | |
# Define getter part | |
$Getter = "return `$this.{0}" -f $Member.Name | |
$Getter = [ScriptBlock]::Create($Getter) | |
# Define setter part | |
$Setter = "Write-Warning 'This is a readonly property.'" | |
$Setter = [ScriptBlock]::Create($Setter) | |
$AddMemberParams = @{ | |
Name = $PublicPropertyName | |
MemberType = 'ScriptProperty' | |
Value = $Getter | |
SecondValue = $Setter | |
} | |
$this | Add-Member @AddMemberParams | |
} | |
} | |
DeathStar () { | |
$this.AddPublicMember() | |
$this._Ready = $true | |
} | |
DeathStar ([int]$ImperialNavy, [int]$Stormtroopers) { | |
$this.AddPublicMember() | |
$this.Crew.ImperialNavy = $ImperialNavy | |
$this.Crew.StormTroopers = $Stormtroopers | |
$this._Ready = $true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment