Home > Software engineering >  Using Invoke command on multiple computers. Need to export some results to location where invoke-com
Using Invoke command on multiple computers. Need to export some results to location where invoke-com

Time:09-08

I am running invoke-command on lots of servers to gather info in parallel. I am then exporting the data locally on the server where the invoke-command is run. Problem i am having is exporting each job as its own unique $server.txt file when i am running invoke-command in parallel.

Contents of servers.txt file Server1 Server2 Server3

Here is my current code..

icm -ComputerName (Get-Content c:\temp\servers.txt) -ErrorAction SilentlyContinue -ThrottleLimit 15 -ScriptBlock{
$A=get some local server info
$B=get some local server info
$C=get some local server info

echo $A,$B,$C} | out-file c:\temp\$server.txt

Problem i have is that i want to export the results as a filename that is the server name the script is running on, and i cannot get the $server variable when using invoke-command to run these jobs in parallel. i dont want to use a foreach loop because thats not in parallel.

i want the output for each serve to be in unique files like this. C:\temp\server1.txt C:\temp\server2.txt C:\temp\server3.txt

EDIT: I guess my other question or workaround would be is there any way to use a variable from inside the invoke-command loop outside? I am gathering the machine name inside the invoke-command, but need to use it to set the filename of the export file.

thank you

CodePudding user response:

invoke-command -ComputerName (Get-Content c:\temp\servers.txt) -ErrorAction SilentlyContinue -ThrottleLimit 15 -ScriptBlock{
    $data = @(
        get some local server info
        get some local server info
        get some local server info
    )
    $server = $env:computername
    $data | set-content c:\temp\$server.txt
}

should do the trick - but you could also receive the data directly:

$result = invoke-command -ComputerName (Get-Content c:\temp\servers.txt) -ErrorAction SilentlyContinue -ThrottleLimit 15 -ScriptBlock{
    $data = @(
        get some local server info
        get some local server info
        get some local server info
    )
    return $data
}

$result | export-csv C:\data.csv -delimiter ";" -noclobber -notypeinformation

CodePudding user response:

I would return an object instead, then you get the pscomputername property added on.

icm localhost,localhost,localhost {  # elevated prompt for this example
  $A,$B,$C=1,2,3
  [pscustomobject]@{A=$A;B=$B;C=$C}
} | ft


A B C PSComputerName RunspaceId
- - - -------------- ----------
1 2 3 localhost      40636f4b-0b65-494f-9912-82464e34c0f2
1 2 3 localhost      857d514c-8080-40ce-8848-d9b62088d75d
1 2 3 localhost      6ee0fd30-fb3a-4ad7-abba-bb2da0fbbece
  • Related