• hi@yahyazahedi.com
  • Germany

Run ESXCLi and ESXi Shell Commands through Powershell

Today, as part of setting up my new VCF lab, I needed to renew all the ESXi certificates in my home lab. Typically, you can regenerate the self-signed certificates on each ESXi host using SSH with the following commands:

/etc/init.d/hostd restart

However, I didn’t want to manually connect to each host via SSH and run the commands. Instead, I looked for a way to automate this process using PowerShell. Here’s the solution I came up with. To connect to the ESXi hosts and run the required commands, I used the Posh-SSH module in PowerShell. This module allows you to establish SSH connections and execute commands remotely.

# Install the Posh-SSH module if not already installed
Install-Module -Name Posh-SSH -Force

# Define the ESXi host details
$esxiHost = "esxi_host_ip"
$username = "root"
$password = "your_password"

# Convert the password to a secure string
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force

# Create the credential object
$credential = New-Object System.Management.Automation.PSCredential ($username, $securePassword)

# Establish the SSH session
$session = New-SSHSession -ComputerName $esxiHost -Credential $credential

# Run the command to regenerate certificates
Invoke-SSHCommand -SessionId $session.SessionId -Command '/sbin/generate-certificates'

# Restart the hostd service
Invoke-SSHCommand -SessionId $session.SessionId -Command '/etc/init.d/hostd restart'

# Close the SSH session
Remove-SSHSession -SessionId $session.SessionId

Share Post on:

Leave a Reply

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