【问题标题】:Run command on all remotes and get results on local machine with powershell在所有遥控器上运行命令并使用 powershell 在本地机器上获取结果
【发布时间】:2018-12-12 20:51:11
【问题描述】:

我想在所有远程服务器(大约 100 台服务器)上远程运行一个命令。这个命令收集所有 iis 并保存在一个 txt 文件中。

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

当然,我的问题是如何在我的本地机器中获取所有远程的列表。我不想收集远程服务器上的每个列表。

$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

【问题讨论】:

    标签: powershell iis powershell-4.0 powershell-remoting


    【解决方案1】:
    1. 创建一个数组来保存结果
    2. 而不是输出它C:\Temp\list.txt 使用,Write-Output 并将其保存到变量中
    3. 只是一个提示,使用 ServerName 的列创建一个自定义对象,以便您可以在结果中识别它。
    4. 将每个结果添加到数组中
    5. 另外你不需要每次都创建一个新会话,只需使用-ComputerName参数

    所以:

    $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)
    
    }
    

    最后,$Array 应该包含所有内容。

    【讨论】:

    • 完美解释,ty :)
    【解决方案2】:

    你可以像这样返回这个文件的内容:

    $Servers = @("remotemachine1", "remotemachine2", "remotemachine3" )
    
    
    foreach ($server in $Servers) {
    
        $PSSession=New-PsSession -ComputerName $server
    
        $result = Invoke-command -Session $PSSession -ScriptBlock {
    
            Write-Verbose -Message "Server: $env:ComputerName" -Verbose
    
    
            return (C:\Windows\System32\inetsrv\appcmd.exe list app)
        }
    
        $result > C:\Temp\list.txt
    }
    Get-PSSession | Remove-PSSession
    

    【讨论】:

    • 也许你还需要一只“猫”,回来后
    【解决方案3】:

    您还可以将调用命令通过管道传输到文件中

    invoke-command -session $pssession -scriptblock { commands on remote machine } | out-file -literalpath "c:\temp\$server-results.txt"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 2018-05-14
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多