Using Invoke-VMScript for running remote scripts on VMs with PowerCLI

Invoke-VMScript allows you to run PowerShell, batch, and Bash scripts on remote VMware virtual machines from PowerShell. Not only that but since you are actually authenticating to vCenter or ESXi, it does not require network connectivity to the server you want to run the script on.

VMware has long supported the use of PowerShell for managing vSphere via PowerCLI. As a VMware Certified Professional (VCP) and PowerShell enthusiast, I have found this to be a great method for managing my own vSphere environments as well. In terms of remoting into my VMware virtual machines (VMs), I typically log in to them the same way I log in to other physical servers via PowerShell remoting.

With that said, there have been instances when I lose network connectivity to a VM. For those cases, Invoke-VMScript, a cmdlet from the PowerCLI module, is a great tool to use. As long as port 902 on the ESXi host is open and the VM has VMware tools installed, you can access it.

How does it work?

According to a VMware technical note, here is the general process of how Invoke-VMScript works:

  1. Detects guest info data for the VM
  2. Determines guest operating system and ensures VM tools is running
  3. Runs PowerShell or Bash based on the operating system
  4. Waits for VM tools to confirm the VM is powered on
  5. Authenticates with the VM with the credentials provided
  6. Creates a temporary file on the VM to store the script’s output
  7. Selects a script interpreter (cmd or Bash)
  8. Runs the script interpreter as a process on the VM
  9. Copies the temporary file to the local computer
  10. Stores the contents of the temporary file in a variable
  11. Deletes the temporary file locally and on the VM
  12. Returns output to your local shell

Testing it out

So to illustrate the lack of dependency on network connectivity to the VM, I will do an experiment. I will disconnect the network interface controller (NIC) from the VM and then attempt to run a remote script. Here, I have a VM called “Test-VM.” As you can see, I can ping it from my local host:

Pinging from local host

Pinging from local host

Now I will disconnect the NIC on the VM via PowerCLI:


Comments are closed.