Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell objects: referencing Self

I can create an object with four properties like this

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

And is works basically as expected. However, I can't seem to grok 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 I can then call $pocketKnife.GetColor() and it works as expected. But I have to hard wire the object reference into the method, and I am actually referencing the object variable defined outside the object itself. What I want to do is

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

Ultimately I want to create a Logger object, that will initialize itself and establish an appropriate log file name in a property, and has a Log method that takes a string argument, and when called it logs to the log file in the property. And I get the sense that maybe this is more than PowerShell is really intended to do with regards to being object oriented. Like I should really be limiting my concept of (custom) objects to Structures for data, not classes and instances? FWIW, I am new enough to OOP that I don't know what I don't know. What I do know is that right now I am using a global variable for the log file path, and init and log functions that reference it, and I am looking for the best way to eliminate the global variable, and also use PS to it's potential, and learn some programming concepts while I am at it. And all my Google Fu ends up with more info about object properties and nothing about methods beyond simple examples that echo some text to prove you're in the method. So, any advice is greatly appreciated, even if it is just "Ain't nothin' up that tree"

Thanks!

like image 358
Gordon Avatar asked Feb 14 '15 14:02

Gordon


1 Answers

PowerShell and C# are very similar. C# uses this to the reference the current instance/itself, while PowerShell uses $this

$This

In a script block that defines a script property or script method, the $This variable refers to the object that is being extended.

Source: about_Automatic_Variables

Sample:

$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
like image 183
Frode F. Avatar answered Nov 15 '22 02:11

Frode F.