Powershell Objects: Self Links

I can create an object with four properties like this

$pocketKnife = New-Object PSObject -property @{
    Color = 'Black'
    Weight = '55'
    Manufacturer = 'Buck'
    Blades = '1'
}

And it works mostly as expected. However, I cannot imagine how to add a method that references the object’s own properties. I can add this

$pocketKnife | Add-Member ScriptMethod GetColor {
    Write-Host "Color = $($pocketKnife.Color)" 
}

and then I can call $ pocketKnife.GetColor () and it works as expected. But I need to hard-link the object reference in the method, and I actually refer to the object variable defined outside the object itself. What I want to do is

$pocketKnife | Add-Member ScriptMethod GetColor {
    Write-Host "Color = $($Self.Color)" 
}

Logger, , , , , , , , , PowerShell, , -. () , ? FWIW, , , . , , init log, , , PS , , . Google Fu , , , , . , , " ".

!

+4
1

PowerShell # . # this /, PowerShell $this

$

script, script script,         $ .

: about_Automatic_Variables

:

$pocketKnife2 = New-Object PSObject -property @{
    Color = 'Black'
    Weight = '55'
    Manufacturer = 'Buck'
    Blades = '1'
}

$pocketKnife2 | Add-Member ScriptMethod GetColor {
    Write-Host "Color = $($this.Color)" 
}

$pocketKnife2.GetColor()
Color = Black

$pocketKnife2.Color = 'Red'

$pocketKnife2.GetColor()
Color = Red
+7

All Articles