Home > Software engineering >  Using $_ export with invoke-command
Using $_ export with invoke-command

Time:09-09

Can someone tell me why this invoke-command is not exporting all the variables?

icm -computername Server1 -scriptblock {
  $A=$env:username;$B=hostname;$C=$env:userdomain;echo $A,$B,$C
} | 
  % {$_ | out-file "c:\temp\$($_.pscomputername).txt"}

The text file only contains "$C=$env:userdomain" variable. How can i export $A,$B,$C variables to the text file while keeping the $_.pscomputername as the name of the exported file?

thank you

CodePudding user response:

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"
  }

CodePudding user response:

This is more typical usage. Instead of format-table, you can pipe to export-csv. It runs in parallel on both computers.

icm -computername com001,com002 -scriptblock {
  [pscustomobject]@{Username=$env:username;
                    Hostname=hostname;
                  Userdomain=$env:userdomain}
} | format-table


Username   Hostname Userdomain PSComputerName RunspaceId
--------   -------- ---------- -------------- ----------
js-adm     COM001   AD         com001         2d660bb5-761c-4e79-9e4f-c3b98f5f8c61
js-adm     COM002   AD         com002         7544a8ff-e419-49c2-9fc3-2a92f50c1424
  • Related