0

Sorry for a confusing title I'm not too sure how to word it exactly. I'm currently working on a PS Network Status bar GUI. In an effort to try and consolidate some lines and try and make things cleaner, I'm trying to Loop the status checks for my status bars. I have my labels made and if I run everything as individual checks it all works but it ends up being a bunch of repeating lines.

So I am trying to make variables for the checks:

$DC1 = Test-Connection "DC1" -Count 2 -Quiet
$DC2 = Test-Connection "DC2" -Count 2 -Quiet

etc, and then run those into a ForEach loop and then update the appropriate status bar.

$Tests = @("$DC1","$DC2")

ForEach($Test in $Tests){
    If($Test -eq $true){
    $(($test).Name)StatusLabel.BackColor = "Green"
    }
}

I know thats not the right way to do that, but I can't think of a way to add Variable 1 name as part of Variable 2's name

Fitzgery
  • 558
  • 5
  • 14
  • If you know what you're doing why not use a selection instead? I don't know how your bars look but something like `($Tests | Where Name -eq "DC1").Statuslabel.Backcolor` should work, shouldn't it? Also `Test-Connection -Computername @("dc1","dc2")` would work as well. Dependend on what you actually need to do. You could use a function for your repeating code. – Seth Aug 30 '21 at 12:17
  • There's the *-variable commands, or you can use a hashtable. – js2010 Aug 30 '21 at 12:18
  • What you're looking for is _variable indirection_, where you refer to a variable _indirectly_, via its name stored in a different variable or provided by an expression. PowerShell enables this via the [`Get-Variable`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-variable) and [`Set-Variable`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/set-variable) cmdlets - see [this answer](https://stackoverflow.com/a/68214332/45375) to the linked duplicate. – mklement0 Aug 30 '21 at 12:21
  • Btw @() is not necessary to make arrays. `$Tests = "$DC1","$DC2"` – js2010 Aug 30 '21 at 16:22

0 Answers0