Author Posts

December 20, 2013 at 8:28 am

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?

December 20, 2013 at 8:31 am

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

December 20, 2013 at 9:15 am

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

December 20, 2013 at 9:17 am

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

December 20, 2013 at 9:32 am

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.