Author Posts

May 19, 2016 at 9:59 am

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.

May 19, 2016 at 10:13 am

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

like so.

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

May 19, 2016 at 10:24 am

You could use -outvariable as well.

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

May 19, 2016 at 11:52 am

Thank you Dan, this helps.