Quantcast
Channel: PowerShell General
Viewing all articles
Browse latest Browse all 10624

Array not populating correctly from foreach loop

$
0
0

Have a report, where I fetch data, but need to insert a field, whose value is derived from what is in another field. Trouble is coming from the foreach loop. Every loop is appending an index into array, but is overwriting every index from the data in the last iteration of the loop. So loop 1 index 1 data loop1, loop 2 index 1 data loop 2 index 2 data loop2, etc. This causes my ending csv to have X rows of data all being the same row repeated over and over.

script I am using:

#Fetch the data
$Fetched_Data_Array = Get-CentralAdminMachine “*<criteria>*” |
select Field_A, Field_B, Field_C, Field_D|
sort-object Field_A, Field_B, Field_C

#Initialize for loops
$Final_Array = @()
$Iteration_Obj = "" | select Location,MachineDefinition,Name,BuildVersion,ProvisioningState,IP,VLAN,AssetNumber,MAC

#Loop data into new array
foreach ($p in $Fetched_Data_Array )
{
 $Iteration_Obj.Field_A = $p.Field_A
 $Iteration_Obj.Field_B = $p.Field_B
 $Iteration_Obj.Field_C = $p.Field_C
 $Iteration_Obj.Field_Cv2 = switch -wildcard($p.Field_C)
 {
  “Condition_1*” {“Yes”; break}
  “Condition_1*” {“No”; break}
  “Condition_1*” {“Maybe”; break}
  default {"Tomorrow"}
 }
 $Iteration_Obj.Field_D = $p.Field_D

    $Final_Array += $Iteration_Obj
}

$Final_Array | export-csv -NoTypeInformation -force temp.csv


Viewing all articles
Browse latest Browse all 10624

Trending Articles