Use Custom Object propery in Custom Object Script

This topic contains 4 replies, has 3 voices, and was last updated by  graybin 3 years, 11 months ago.

  • Author
    Posts
  • #12050

    graybin
    Participant

    I want to create a custom object with some properties, and some scripts that use those properties. I can figure out how to access the properties from within the script. Function that creates the object. Once property is "Count". I have a ScriptMethod called "Step" that I would like to refer to the "Count" property defined.

    Function Create-ProgressBar{
    $ProgressBar = New-Object –TypeName PSObject
    $ProgressBar | Add-Member –MemberType NoteProperty –Name ....
    $ProgressBar | Add-Member –MemberType NoteProperty –Name Count -Value 10
    $ProgressBar | Add-Member –MemberType NoteProperty –Name X -Value 0
    $ProgressBar | Add-Member –MemberType NoteProperty –Name Increment -Value .25
    $ProgressBar | Add-Member –MemberType NoteProperty –Name ....
    .
    .
    .
    $ProgressBar | Add-Member –MemberType ScriptMethod –Name Step -Value {$_.X = $_.Increment*$_.Count}
    }
    
    $PB = Create-ProgressBar
    $PB.Step()
    

    I though '$_' would work, but it doesn't. How do I do this?

  • #12051

    Richard Siddaway
    Moderator

    Is there a reason you are creating your own progress bar instead of using Write-Progress?

  • #12052

    graybin
    Participant

    Yes, I want to do some different things, but I am looking at how to do this in general for other applications as well.

  • #12053

    Dave Wyatt
    Moderator

    Inside your script block, use the $this automatic variable instead of $_. I assume you meant that to be a += operator, not = (or Step would always assign the same value to X, over and over.)

    $ProgressBar | Add-Member –MemberType ScriptMethod –Name Step -Value { $this.X += $this.Increment * $this.Count }

    Richard's got a point, though, you're kind of reinventing the wheel here. PowerShell has the Write-Progress cmdlet, and if that doesn't meet your needs, you can also easily access the System.Windows.Forms.ProgressBar class, which has similar functionality to what you've shown so far (X = Value, Increment / Count = Step, Step() = PerformStep() , etc)

    Add-Type -AssemblyName System.Windows.Forms
    $PB = New-Object System.Windows.Forms.ProgressBar
    
  • #12054

    graybin
    Participant

    Thanks, $This worked.

    I am playing with the progress bar to see what I can do. I have looked at the System.Windows.Forms.ProgressBar also, and it doesn't really have what I want either.

You must be logged in to reply to this topic.