Wednesday, June 20, 2012

PowerShell: Run Commands Remotely from an AD List

This is a basic example of getting a list of computers from a specific OU in Active Directory and running commands against each remote machine. 

Import-Module ActiveDirectory
$list = Get-ADComputer -filter * -SearchBase "OU=Desktops,OU=Computers,DC=Contoso,DC=com"
foreach ($computer in $list) {
      Invoke-Command -ComputerName $computer.name -ScriptBlock {
           Get-Service
      }
}


The Active Directory module is imported (included in PowerShell 2.0) which contains all the Cmdlets we will need to work with AD. 

Import-Module ActiveDirectory

The Get-ADComputer Cmdlet searches for all computers (hence the filter * or "all") in the Organizational Unit specified and saves it as an array in the variable $list. 

$list = Get-ADComputer -filter * -SearchBase "OU=Desktops,OU=Computers,DC=Contoso,DC=com"

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

}

$computer.name pulls out just the name of the computer from the object carried in the $computer variable (not the SID or any other information not needed).

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