I can't for the life of me work out how to add elements to an array inside a foreach loop. I keep getting the error:
8 | $logs.Add(@{
| ~~~~~~~~~~~~
| Cannot find an overload for "Add" and the argument count: "1".
MethodException: C:\Users\michael.dawson\OneDrive - Sage Software, Inc\Documents\Source_Control\secrets-dashboard-script\function\Calculate\recreate-error2.ps1:8:5
I can get it to work outside of a foreach, but I've been scratching my head for ages :-( Here's the code:
$logs = New-Object System.Collections.ArrayList
$logs = $null
$logs = @{}
Get-Service | ForEach-Object {
$appCreds = $_
$logs.Add(@{
"test" = $appCreds.DisplayName;
"message" = "blah"
})
}
$logs | ConvertTo-Json -Depth 10
Appreciate any help guys. Cheers.
I'm expecting some JSON a bit like this:
{
"message": "blah",
"test": "Optimise drives"
},
{
"message": "blah",
"test": "Dell Client Management Service"
},
{
"message": "blah",
"test": "DeviceAssociationBroker_1592b90"
}
CodePudding user response:
Try the following:
$logs =
Get-Service |
ForEach-Object {
@{
test = $_.DisplayName;
message = "blah"
}
}
$logs | ConvertTo-Json -Depth 10
CodePudding user response:
I am in rush but, I want to help. Try the example below.
$logs = New-Object System.Collections.ArrayList
Get-Service | ForEach-Object {
$appCreds = $_
$logs.Add(@{
"test" = $appCreds.DisplayName;
"message" = "blah"
}) | out-null
}
$logs | ConvertTo-Json -Depth 10