Search code examples
powershellvmwarepowercli

How to run VMware commands from remote scripts on windows


Have a local basic Powershell form for searching and creating VMware virtual machines.

Using new powershell powerCLI module, as described in link

Let's take Get-VM for example:

LOGIC: Type a certain string in TextBox > click search > prints VM's status/parameters in the form

The problem is, I can't execute Get-VM straight away from the script, but first have to connect using Connect-VIServer command and only than Get-VM will work

Is there any way to do it from the script? Something similar to -m flag of commands plink or putty.

Like: Connect-VIServer -server testvc -flagForExample "commands_list.txt"


Solution

  • Yes, you can. Before providing an immediate answer I'd like to explain what is actually happening. When you call Connect-VIServer the command sets the value of the variable $DefaultVIServer behind the scenes, which is later used by other cmdlets (such as Get-VM).

    However, the Get-VM documentation states that there is a Server parameter available. Which means that you can store your server connection in a variable and then pass it to the Get-VM cmdlet.

    Here's a pseudo-code example: $server = Connect-VIServer -server testvc Get-VM -Server $server

    Furthermore, the Get-VM supports an array of servers, so theoretically you can run the cmdlet on multiple servers at once. For example: $server1 = Connect-VIServer -server testvc $server2 = Connect-VIServer -server testvc2 Get-VM -Server @($server1, $server2)