Run PowerShell on All Machines in Active Directory Group

Easily run PowerShell on every machine in an Active Directory group.

John Savill

June 11, 2014

1 Min Read
PowerShell command prompt

Q: How can I run any PowerShell command on every machine in an Active Directory group?

A: I wrote the following PowerShell code as a way to run any PowerShell command on every machine in an Active Directory (AD) group. Pass it the group name and then the PowerShell command to run, and it will run the command on every machine in the passed group.

[CmdletBinding()]Param(    [Parameter(Mandatory=$true, Position=1)][string]$ADGroupName,    [Parameter(Mandatory=$true, Position=2)][string]$CommandToRun)$ScriptBlockContent = {     param ($CommandToRun)    Invoke-Expression $CommandToRun }$ADGroupMembers = Get-ADGroupMember -Identity $ADGroupNameforeach ($computer in $ADGroupMembers){    #Run the required command on each computer in the group    Invoke-Command -ComputerName $computer.name -ScriptBlock $ScriptBlockContent -ArgumentList $CommandToRun}

The following code shows a very simple use that simply creates a folder on all machines in the passed AD group. Note that the command to run must be placed in double quotes.

PS C:UsersadministratorDocuments> .RunCommand.ps1 FileServicesGroup "mkdir 'c:ewtest file3'"Directory: C:Mode     LastWriteTime     Length     Name             PSComputerName ----     -------------     ------     ----             -------------- d----   5/27/2014 1:29 PM             newtest file3    SAVDALISCSI01 d----   5/27/2014 1:29 PM             newtest file3    SAVDALFS01 

I decided to take this functionality even further and enable it as a service request via the Service Manager web portal, triggered through Orchestrator. For the full solution, see my blog post "A whole bunch of stuff with Service Manager." This blog post also includes a link to a 45-minute video that walks through the solution.

About the Author

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like