I was recently helping a friend of mine who wanted to execute a single command on thousands of ESXi hosts and was looking for an easy way to do this. Enter PowerCLI, which is why this post is titled PowerCLI - How to execute script remotely on ESXi hosts.
At first, I did a quick google search and it led to the community forum https://communities.vmware.com/thread/558507, but there were slight changes that were required for this to work.
We will be making use plink software, it is a command-line connection tool similar to UNIX ssh. It is mostly used for automated operations like scripting, etc.
The latest version can be downloaded from http://the.earth.li/~sgtatham/putty/0.63/x86/
So without further ado, here is the script that I wrote and executed on a single ESXi host, the same logic to any number of hosts that you would want to run this on.
$root = "root" $Passwd = "VMware1!" $esxlist = "192.168.0.200" $cmd = "esxcli storage filesystem list" $plink = "echo y | C:\Users\administrator\Downloads\plink.exe" $remoteCommand = '"' + $cmd + '"' foreach ($esx in $esxlist) { Connect-VIServer $esx -User $root -Password $Passwd Write-Host -Object "starting ssh services on $esx" $sshstatus= Get-VMHostService -VMHost $esx| where {$psitem.key -eq "tsm-ssh"} if ($sshstatus.Running -eq $False) { Get-VMHostService | where {$psitem.key -eq "tsm-ssh"} | Start-VMHostService } Write-Host -Object "Executing Command on $esx" $output = $plink + " " + "-ssh" + " " + $root + "@" + $esx + " " + "-pw" + " " + $Passwd + " " + $remoteCommand } $message = Invoke-Expression -command $output $message
Let me give you a brief understanding of what the script does.
We are first setting up some variables for the user account and password and the command that we need to execute remotely.
In my case, as a proof of concept, I am just listing the volumes available on the ESXi host.
$esxlist only has one host, but you can easily use a .csv and import many more hosts and run the foreach loop shown.
We have some error handling in the foreach loop, where it will enable the SSH service on the host it isn't already.
The final step is to execute script remotely on ESXi hosts and save the output in a variable called $message and echo the same on the screen.
I hope this has been informative and thank you for reading!
1 Comment
Thanks for this. I used it to remove a file filling up the /tmp folder on many hosts.