1

My current goal is to create a function that can produce $ProgressBar1, $ProgressBar2, and so on. While defining the name as such and giving it the appropriate definitions below. Like size and location.

This is for an overly complex Powershell Script w/GUI and I will calling upon a listbox populated with any number of items to a Foreach{MakeBar}. The bars will monitor the task progress.

$counter = 0 is currently defined at the script level.

function MakeBar
{

New-Variable -Name "ProgressBar$script:counter"

ProgressBar$script:counter = New-Object 'System.Windows.Forms.ProgressBar'
$loc = ((23 * $script:counter) + 12)
ProgressBar$script:counter.Location = '94, $loc'
ProgressBar$script:counter.Name = 'progressbar1'
ProgressBar$script:counter.Size = '1109, 23'
ProgressBar$script:counter.TabIndex = 1
$script:counter++
}

I've been warned about modifying things outside of current scope but I am not sure how else or how best to accomplish this in Powershell.

2
  • 2
    MakeBarshould return a System.Windows.Forms.ProgressBar which you can store in an array / list instead of using variable counters. Commented Mar 29, 2016 at 9:12
  • you might also be able to use a hash table to store multiple progress bars. $bars = @{'Progress1' = {<#MakeBar#>}; 'Progress2' = {<#MakeBar#>}} Commented Mar 29, 2016 at 12:11

1 Answer 1

1

I would recommend to have the function create the progress bar according to parameters passed into it (note that you must use double quotes if you want variables expanded in strings):

function New-ProgressBar([int]$index) {
  $bar = New-Object Windows.Forms.ProgressBar
  $loc = (23 * $index) + 12
  $bar.Location = "94, $loc"
  $bar.Name = "progressbar$index"
  $bar:counter.Size = '1109, 23'
  $bar.TabIndex = $index

  return $bar
}

and do all the counter handling and variable assignments in the loop(?) where you call the function:

$counter = 0
foreach (...) {
  New-Variable -Name "ProgressBar$counter" -Value (New-ProgressBar $counter)
  $counter++
}

Personally I'd prefer putting the progress bars into a hashtable rather than individual variables, though:

$counter  = 0
$progress = @{}
foreach (...) {
  $progress["Bar$counter"] = New-ProgressBar $counter
  $counter++
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.