Wednesday, June 20, 2012

PowerShell: Run Commands Remotely from a List of Machines in a Text File

This is a basic example of getting a list of computers from a text file and running commands against each remote machine. 

$list = Get-Content "c:\Myfolder\RemoteComputers.txt"
foreach ($computer in $list) {
    Invoke-Command -ComputerName $computer.name -ScriptBlock {
        Get-Service
    }
}

The Get-Content Cmdlet will pull the list of computers from the text file specified and save them as an array in the variable $list.

$list = Get-Content "c:\Myfolder\RemoteComputers.txt"

The foreach loop automatically moves each object (the information from each computer that was pulled from AD such as name, SID, etc) and applies it to the variable $computer.

foreach ($computer in $list) {
      Invoke-Command -ComputerName $computer.name -ScriptBlock {
           Get-Service
      }

}

The Invoke-Command remotely connects to the computer saved in the variable $computer and runs the commands in the scriptblock and returns the output for us to see (here we get a list of Windows services).

Invoke-Command -ComputerName $computer.name -ScriptBlock {
      Get-Service

}

Invoke-Command will only be able to connect to a computer if you have previously setup Windows Remote Management (Winrm) on each machine you need to connect to. Winrm is disabled by default and will be discussed in a later post.

No comments:

Post a Comment