Using Invoke-Command In PowerShell

In this article, Dan Franciscus covers how to use the Invoke-Command and why it is one of his favorite commands to use in PowerShell.

Ever since I started using PowerShell as my command prompt and scripting language, there are various cmdlets that I admire. To me, Invoke-Command has been my favorite cmdlet to use for a few years and for good reason.

Invoke-Command simply runs a script block or script locally or on remote computers. The power that Invoke-Command has though, is the way in which it does this, in parallel. Meaning, I could write one command that will run on multiple machines at the same time and either return output to the console or run as a background job. The use cases for using Invoke-Command are immense, but one of my favorite is for installing software remotely with Chocolatey.

In this article, I will go over some demonstrations of how I use Invoke-Command.

Running commands remotely

So, what I would strongly recommend, is that before you use Invoke-Command, you enable PowerShell remoting on the machines you will be connecting to. There are various ways to do this, but it means you need to enable port 5985 and allow the WinRM service on remote machines to listen for remoting. This can be set up easily through group policy. The best part is that Kerberos handles authentication, so no need to pass credentials.

Once remoting is enabled on remote machines, we can run Invoke-Command:

Awesome right? We just ran Get-Service on our remote machine and it returned the output right to my local console.

So what about running a script on many machines at once? Well something I do often is query Active Directory for machine names that I want to run a script on. For this, I can use Get-ADComputer:


Leave a Reply

Your email address will not be published. Required fields are marked *