Skip to content

Instantly share code, notes, and snippets.

@pcgeek86
Last active August 29, 2015 14:02
Show Gist options
  • Save pcgeek86/3ea6936bb58956f9452e to your computer and use it in GitHub Desktop.
Save pcgeek86/3ea6936bb58956f9452e to your computer and use it in GitHub Desktop.
PowerShell Add-Member Examples
# 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