by Klaus Graefensteiner
17. December 2009 10:41
Introduction
Yesterday at the gym I was listening to the PModem show of the PowerScripting Podcast and suddenly I noticed that I rolled my own version of the Select-Object cmdlet for a blog post that I published a few days ago: Using Partial Clones for TDD and Polymorphism in PowerShell. In this blog post I replace my version of cloning selected properties with the Select-Object cmdlet.
Figure 1: Never roll your own roller coaster
Changes
Figure 2: This screenshot shows the diff report generated with Winmerge
New Version
Here is the new version of the script that uses the Select-Object cmdlet
set-debugmode
function Clone-AsStub()
{
[CmdletBinding(DefaultParameterSetName="Full")]
param
(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNull()]
[PSObject] $ObjectToClone,
[Parameter(Position=1, Mandatory=$false, ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[string[]] $PropertiesToClone,
[Parameter(Position=2, Mandatory=$false, ValueFromPipeline=$false)]
[switch] $PreserveTypeInfo,
[Parameter(Position=3, Mandatory=$false, ValueFromPipeline=$false, ParameterSetName="Magic")]
[ValidateNotNull()]
[ScriptBlock] $RevertScriptBlock
)
process
{
$Clone = $ObjectToClone | Select-Object -Property $PropertiesToClone
if($PreserveTypeInfo)
{
$Clone = Add-Member -InputObject $Clone -MemberType "NoteProperty" -Name "TypeName" -Value $ObjectToClone.GetType().FullName -PassThru
}
if( $PsCmdlet.ParameterSetName -eq "Magic")
{
$Clone = Add-Member -InputObject $Clone -MemberType "ScriptMethod" -Name "Revert" -Value $RevertScriptBlock -PassThru
}
return $Clone
}
}
Download
The new version of the script can be downloaded here: NewVersionWithSelectObject.zip
Ausblick
Rolling your own version of Select-Object is a good exercise, but at the end I would rather use Select-Object in production.