I can't figure out what I'm doing wrong and hope someone can point me in the right direction.
I'm trying to iterate through an array of objects and testing on each object and when something is true, I want to take that object and add it to it's own array, as a single object (just like it was in the original array of objects). I seem to be adding the information to the new array, but when I reference the new array by doing newarray[0] it gives me the first item of the object, not the entire object itself.
The issue appears to be with this line:
$global:MachinesInAD += $global:MachineObject
The data in the csv file is a machine hostname, the machines IP address, an error code, and an agent ID.
e.g. MACHINENAME, 10.10.10.10, ERROR101, 123456FF
Function ReadExcelReport (){
$global:Report = "C:\TEMP\Tools\Scripts\agents.csv"
$Unresponsive = import-csv $global:Report | Where-Object {($_.State -eq "QUEUED" -or $_.State -eq "FAILED")} #Add items to array from spreadsheet where the state is equal to queued or failed
$global:UnresponsiveMachineInfo = @()
foreach ($item in $Unresponsive){
$global:UnresponsiveMachineInfo += ,@($item.'Hostname', $item.'IP Address',$item.'Error',$item.'Agent Cert ID') #Build the object - Add the following columns hostname, ip address, error, agent cert id
}
ADCheck
}
Function ADCheck (){
$Machine = $null
$global:MachinesInAD = @()
$global:MachinesNotInAD = @()
$global:MachineObject = New-Object system.object
$global:MachineObject = $Null
$global:MachinesInAD = $null
$global:UnresponsiveMachineInfo | foreach-object { #Iterate through each object in the array
$global:MachineObject = $_
$Machine = $_[0] #Set Machine to the hostname AKA the first element in the array for the current ($_) object (objects defined above)
try{
write-host "Checking A.D. for: $Machine"
if (Get-ADComputer $Machine){ #Check to see if the machine is in A.D.
write-host "Found $Machine in A.D." -ForegroundColor Green
$global:MachinesInAD += $global:MachineObject
}
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] { #If the machine was NOT in A.D. catch the error it creates and...
write-warning -message "Machine $Machine not found in A.D."
$global:MachinesNotInAd += $MachineObject
}
}
}