The problem with your approach is that each individual object output by icm
(Invoke-Command
) causes the output file passed to Out-File
in the %
(ForEach-Object
) script block to be rewritten, so that you end up with only the last one in the file.
Toni makes good points about the values you're returning from your remote script block, and about collecting the information in a single object, which solves your problem.
Applying the same idea to the multiple values you're trying to return, you can return them as a single array, as a whole, so that you only have one object to write, which contains all the information.
To that end, you not only must construct an array, but also prevent its enumeration on output, which is most easily done by using the unary form of ,
to create an aux. wrapper array (alternatively, use Write-Output -NoEnumerate
; see this answer for more information).
icm -computername Server1 -scriptblock {
# Return the values as a single array, wrapped in
# in a aux. array to prevent enumeration.
, ($env:username, (hostname), $env:userdomain)
} |
% {
# Now each targeted computer returns only *one* object.
$_ | out-file "c:\temp\$($_.pscomputername).txt"
}