Created
August 8, 2012 19:02
-
-
Save abombss/3297608 to your computer and use it in GitHub Desktop.
PSAddMember -- Extend all objects with an easier to use PSAddMember function
This file contains hidden or 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
Function PSAddMember() { | |
$this = $args[0] | |
switch($args.Count) { | |
2 { | |
($args[1] -as [HashTable]) | %{ $_.GetEnumerator() } | %{ Add-Member -InputObject $this -Name $_.Name -value $_.Value -MemberType Noteproperty -Force -PassThru } | |
break; | |
} | |
3 { | |
Add-Member -InputObject $this -Name $args[1] -value $args[2] -MemberType Noteproperty -Force -PassThru | |
break; | |
} | |
4 { | |
Add-Member -InputObject $this -Name $args[1] -value $args[2] -MemberType $args[3] -Force -PassThru | |
break; | |
} | |
} | |
<# | |
.SYNOPSIS | |
Quickly adds a member property to object. Once System.Object is extended with this method then extending objects is trivial | |
.EXAMPLE | |
# Get-Process | %{ $_.PSAddMember("Author", "Me").PSAddMember("Thread-Count", { $this.Threads.Count }, "ScriptProperty") } | Select Name,Author,Thread-Count | |
Description | |
----------- | |
Quickly add note properties or custom properties | |
You can chain multiple calls together and continue passing the objects through the pipeline | |
.EXAMPLE | |
# Get-Process | %{ $_.PSAddMember(@{Author=Me;Thread-Count=($_.Threads.Count)}) } | Select Name,Author,Thread-Count | |
Description | |
----------- | |
Use a hashtable to add a bunch of properties at once. | |
Note that any expressions for the property value are executed when added | |
and the resulting value of the xpression is stored in a NoteProperty value. | |
#> | |
} | |
# Extend every object in the powershell system with a PSAddMember function | |
# PS 3.0 Only, < 3.0 requires using an xml type file and loading that | |
Update-TypeData -TypeName System.Object -MemberName PSAddMember -MemberType ScriptMethod -Value { PSAddMember $this @args } -Force |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment