Here's a fast and concise PSv4+ solution that utilizes LINQ:
(Get-Content numbers.txt).ForEach({
[Linq.Enumerable]::Sum([int[]] ($_ -split ' '))
})
Here's a - slower - solution closer to what you attempted (works in PSv3- too):
Get-Content numbers.txt | ForEach-Object { # Process each line.
$sum = 0 # initialize the sum (implicitly of type [int])
foreach ($num in $_ -split ' ') { # Process all tokens on the line.
# Note: Because $sum is [int]-typed, adding the *string* token at
# hand implicitly converts it to [int].
$sum += $num
}
$sum # Output the sum - do NOT use Write-Host to output DATA
}
Both solutions yield the following:
14 # 2 + 3 + 4 + 5
11 # 5 + 6
20 # ...
174
1128
126
As for what you tried:
Get-Content -Delimiter " " numbers.txt
This splits your entire file into a single array of number strings, ignoring line boundaries.
Instead, you must use Get-Content
as-is in order to process the file line by line, and then split each line into space-separated tokens to sum up.