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  Ed O’Connor 1 year, 7 months ago.

  • Author
    Posts
  • #39285

    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

    Dan Potter
    Participant

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

    like so.

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

  • #39289

    Dan Potter
    Participant

    You could use -outvariable as well.

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

  • #39302

    Ed O’Connor
    Participant

    Thank you Dan, this helps.

You must be logged in to reply to this topic.