I am working on a simple script to learn PowerShell. The script code follows. The basic issue is:
(a) An $dataArray = @() is defined.
(b) An $dataObject (PSObject) is created and populated with data
(c) code line is intended to store data: $dataArray += $dataObject
Problem: The code line executed. 1st time line is executed, $dataObject content is stored in $dataArray[0]. 2nd time line is executed, new $dataObject is stored in $dataArray[0] and repeat $dataArray[1]. 3rd time line is executed, new $dataObject is stored in $dataArray[0] and repeat $dataArray[1] and $dataArray[2]. The end result is that the content of the last $dataObject filled the array. All previous data was lost.
Objective: My objective is to maintain the integrity of the $dataArray to dump it at the end.
The Code:
$dataArray = @() # Array to store data $outputProperty = @{ Hostname = $Null IPv4 = $Null IPv6 = $Null MAC = $Null MACDesc = $Null } $dataObject = New-Object -TypeName PSObject -Property $outputProperty $Computers = Get-ADComputer -filter * | select -expandproperty name Foreach($Machine in $Computers) { $pObject = '' $pObject = (Test-Connection -Cn $Machine -BufferSize 16 -Count 1) If($pObject) { $colItems = get-wmiobject -class "Win32_NetworkAdapterConfiguration" -computername $Machine foreach ($objItem in $colItems) { if($objItem.DefaultIPGateway -gt "") { $dataObject.MACDesc = $objItem.Description $dataObject.MAC = $objItem.MACAddress } } # foreach ($objItem in $colItems) $dataObject.Hostname = $pObject.address [string]$dataObject.IPv4 = $pObject.IPv4address -split [char]13 [string]$dataObject.IPv6 = $pObject.IPv6address -split [char]13 $dataArray += $dataObject } # If($pObject) } # Foreach($Machine in $Computers) $dataArray