Search code examples
powershelliispowershell-4.0powershell-remoting

Run command on all remotes and get results on local machine with powershell


I want to run one command remotely on all remotes server(roughly 100 servers).This command collecting all iis and saving in a txt file.

(C:\Windows\System32\inetsrv\appcmd.exe list app >C:\Temp\list.txt)

Naturally my problem is how to get one list of all remotes in my local machine.I dont want to collect each list on remotes servers.

$Servers = @("remotemachine1", "remotemachine2", "remotemachine3" )


foreach ($server in $Servers) {

    $PSSession=New-PsSession -ComputerName $server

    Invoke-command -Session $PSSession -ScriptBlock {

        Write-Verbose -Message "Server: $env:ComputerName" -Verbose


        C:\Windows\System32\inetsrv\appcmd.exe list app >C:\Temp\list.txt

    }
}
Get-PSSession | Remove-PSSession

Solution

    1. Create an array to hold the results
    2. Instead of output it C:\Temp\list.txt use, Write-Output and Save it to a Variable
    3. Just a tip, Create a custom Object with Column for ServerName so you can identify it in the results.
    4. Add each result to the Array
    5. Also you don't need to create a new session each time, just use the -ComputerName Parameter

    So:

    $Array = New-Object System.Collections.ArrayList
    $Servers = @("remotemachine1", "remotemachine2", "remotemachine3" )
    
    foreach ($server in $Servers) {
    
    $Results = Invoke-command -ComputerName -ScriptBlock {
        Write-Verbose -Message "Server: $env:ComputerName" -Verbose
        Write-Output (C:\Windows\System32\inetsrv\appcmd.exe list app)
    }
    
    $Row = "" | Select Server,Results
    $Row.Server = $Server
    $Row.Results = $Results
    [void]$Array.Add($Row)
    
    }
    

    Finally the $Array should hold it all.