Can I create a Dynamic Variable name that increment with each loop of a for/each

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Ed O'Connor Ed O’Connor 6 months, 2 weeks ago.

  • Author
    Posts
  • #39285
    Profile photo of Ed O'Connor
    Ed O’Connor
    Participant

    I am trying to wrap my head around something and could use some assistance.

    I have a variable that has x amount of server names in it via a AD query

    $Nodes = Get-ADComputer -SearchBase "OU=DSC Managed Nodes,OU=SERVERS,OU=NYC,OU=Americas,DC=lab2,DC=test,DC=com" -Filter * | Select-Object Name
    

    What I want to do next is run a command against each of those nodes and have the output for each node put into it's own separate variable

    $DSCStatus =  Foreach ($Node in $Nodes.name)
                            {
                                Try 
                                {
                                    Test-DSCConfiguration -computername $Node –detailed -ErrorAction STOP  | select-object PSComputerName,InDesiredState,@{ Name = "Resources In Desired State" ; Expression = {$_.ResourcesInDesiredState}},@{ Name = "Resources Not In Desired State" ; Expression = {$_.ResourcesNotInDesiredState}}
                                }
                                Catch 
                                {
                                    $_
                                }
                    }
    

    My question how can I take the code above and have the results of the try/catch put into a separate variable for each server?

    So I would be looking for on the first cycle (first node) through it puts the output into something like $Data1, then on the second cycle (second node) it puts the output into something like $Data2, and so on with each $DataX incrementing with each cycle.

    This would need to by dynamic as computers will be added to the OU and need to be accounted for without having to modify the script each time.

    Thanks in advance for some guidance.

  • #39287
    Profile photo of Dan Potter
    Dan Potter
    Participant

    new-variable -name "data$int" -value $something

    like so.

    (1..10) | % {new-variable -Name "data$_" -value $_ }
    get-variable

  • #39289
    Profile photo of Dan Potter
    Dan Potter
    Participant

    You could use -outvariable as well.

    $user = 'me';get-aduser me -OutVariable $user

  • #39302
    Profile photo of Ed O'Connor
    Ed O’Connor
    Participant

    Thank you Dan, this helps.

You must be logged in to reply to this topic.