简体   繁体   English

Powershell 从 foreach 循环创建新变量以在循环外使用

[英]Powershell create New-Variable from foreach loop to be used outside of the loop

So I am pulling in an array and then cleaning it to just the unique values I need and then running that though a foreach loop to create所以我拉入一个数组,然后将其清理为我需要的唯一值,然后通过 foreach 循环运行它以创建

$ZoneArray = Import-Csv -Path "Test.csv" | select Zone
$Zones = @()
foreach ($Zone in $ZoneArray){
        $Zones += $Zone.Zone
}
$Zones = $Zones | select -Unique

foreach ($ZonesTest in $Zones){
            Set-Variable -Name "Zone$_" -Value $ZonesTest -Force
    
            New-UDTab -Text $ZonesTest -Content {
                    New-Variable -Name 'CurrentZone'
                    New-UDmuButton -Id 'Zone1Test' -Text ( + " On") -Variant contained -FullWidth -OnClick {
                            Show-UDToast -Message "Starting" -Duration 1000 -Position center
                            $ZoneFullArray = $FullArray | Where-Object Zone -eq $ZonesTest
                            foreach ($ZoneFullArrayTest in $ZoneFullArray){
                                    Set-UDButtonStateChange -Id 'Zone1Test' -Text $ZoneFullArrayTest.ReceiverIPAddress
                                    Start-Sleep -Milliseconds 1000
                            }
                    }
            }
    }

Using Set-Variable -Name "Zone$_" -Value $ZonesTest -Force I am able to call the correct value while it is running.使用Set-Variable -Name "Zone$_" -Value $ZonesTest -Force我可以在它运行时调用正确的值。 I have tried using我试过使用

$Q=1
Set-Variable -Name "Zone$Q" -Value $ZonesTest -Force`
$Q++

But then I don't know how to dynamically call back the correct $Zone$Q for the later button press.但后来我不知道如何动态回调正确的 $Zone$Q 以便稍后按下按钮。

Is there anyway to program a dynamic variable that remembers the state it was made and then I can recall it later without knowing it's name?有没有办法编写一个动态变量来记住它的状态,然后我以后可以在不知道它的名字的情况下回忆它? I know that sounds really confusing.我知道这听起来很令人困惑。

Ideas?想法?


Edit:编辑:

I am banging my head against the wall.我正用头撞墙。 I know that the $ZoneFullArray = ... and foreach ($ZoneFullArrayTest in $ZoneFullArray){... is what is breaking it but can't think of another way to write it.我知道$ZoneFullArray = ...foreach ($ZoneFullArrayTest in $ZoneFullArray){...是什么破坏了它,但想不出另一种写法。 The problem I am trying to solve with the second foreach to create a button dynamically based off the CSV table and then pull the value of the IP addresses that match the main row value making $Zones .我试图用第二个foreach解决的问题是根据 CSV 表动态创建一个按钮,然后提取与主行值匹配的 IP 地址值,从而生成$Zones The issue is that the code within the button is not run until it is pressed so it is hard to write them dynamically.问题是按钮中的代码在按下之前不会运行,因此很难动态编写它们。

So I ended up using the code blocks @mklement0 suggested but added the param option I found to pass data into the code block.所以我最终使用了@mklement0 建议的代码块,但添加了我发现的参数选项来将数据传递到代码块中。

$CodeBlock = { param($par1, $par2)
foreach ($Row in $par1){
        $SwitchIPCurrent = $Row.SwitchIP
        $SwitchUsernameCurrent = $Row.SwitchUsername
        $SwitchPasswordCurrent = $Row.SwitchPassword
        $SwitchPortCurrent = $Row.SwitchPort
}
}

To run the code just pass the param into the code block要运行代码,只需将参数传递到代码块中

&$CodeBlock -par1 $ImportedArray -par2 $Variable

As iRon points out, variable indirection (referring to variables indirectly , via dynamically created variable names) is best avoided - see this post .正如iRon指出的那样,最好避免变量间接(通过动态创建的变量名间接引用变量) - 请参阅这篇文章

It sounds like what you're really looking for are script-block closures that lock in then-current variable values in each iteration of a loop, along the following lines:听起来您真正要寻找的是脚本块闭包,它们在循环的每次迭代中锁定当时的变量值,如下所示:

# Sample input zones.
$zones = 'foo', 'bar', 'baz'

# Create a script block with a closure for each zone.
$scriptBlocks = 
 foreach ($zone in $zones) {
   # .GetNewClosure() locks in the iteration-specific value of $zone
   { "This zone: $zone" }.GetNewClosure()
 } 

# Execute the script blocks to demonstrate that the values where
# captured as intended.
$scriptBlocks | ForEach-Object { & $_ }

Output:输出:

This zone: foo
This zone: bar
This zone: baz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM