Last active
August 29, 2015 14:02
-
-
Save pcgeek86/3ea6936bb58956f9452e to your computer and use it in GitHub Desktop.
PowerShell Add-Member Examples
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
# Create a new object | |
$Person = [PSCustomObject]@{ | |
FirstName = 'Nickolaj'; | |
LastName = 'Andersen'; | |
Age = 27 | |
}; | |
# Add a custom "type" name to the object called "Person" | |
$Person.pstypenames.Add('Person'); | |
# EXAMPLE #1: Add a GetFullName() method, that simply concatenates the first & last names of a Person | |
$FullNameMethod = { '{0} {1}' -f $this.FirstName, $this.LastName; }; | |
Add-Member -InputObject $Person -MemberType ScriptMethod -Name GetFullName -Value $FullNameMethod; | |
# TEST: Get the Person's full name | |
$Person.GetFullName(); | |
# EXAMPLE #2: Add a Validate() method that ensures the Person object meets type requirements | |
$ValidateMethod = { $this.FirstName.Length -ge 2 -and $this.FirstName.Length -lt 20; }; | |
Add-Member -InputObject $Person -MemberType ScriptMethod -Name Validate -Value $ValidateMethod; | |
# TEST: Test out the Validate() method | |
$Person.Validate(); # Validate the Person object. Should return $true, because the first name is longer than 2, and less than 20 characters | |
$Person.FirstName = 'a'; # Change the person's first name | |
$Person.Validate(); # Returns $false, because first name is only one character |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment