PowerShell PowerCLI Script for testing vMotion on all Hosts for Each VM

185 Views Asked by At

I am looking for a quick way to check all of my VMs and Hosts for vMotion Compatibility. Here is what I have gotten so far.

#Start Script
Start-Transcript -Path "\\Server.Name\Department\InformationTechnology\VMware\PowerShell\Logs\vMotion-Data_$(Get-Date -Format `"yyyymmdd_hhmmtt`").txt" -IncludeInvocationHeader

#Connection Data
$vCenterServerName = Read-Host "What is the vCenter Server IP?"
$Username = Read-Host "What username?"
$Password = Read-Host "What password?" -AsSecureString 

Connect-VIServer -Server $vCenterServerName -user $Username -password $Password

# Find all Hosts and VMs
$hosts = Get-VMHost
$vmhosts = $hosts | Get-VM

# Loop through each host and check vMotion compatibility
foreach ($host in $hosts) {
    # Check if vMotion is enabled on the host
    if ($host.ExtensionData.Config.Network.VmotionEnabled) {
        Write-Host "vMotion is enabled on Host $($host.Name)"
        # Check vMotion compatibility for each VM on the host
        foreach ($vm in $vmhosts | where {$_.VMHost.Name -eq $host.Name}) {
            $vmotionCompatibility = $vm | Test-VMHost -VMotion
            if ($vmotionCompatibility.Compatible) {
                Write-Host "vMotion is compatible for VM $($vm.Name) on Host $($host.Name)"
            } else {
                Write-Host "vMotion is not compatible for VM $($vm.Name) on Host $($host.Name): $($vmotionCompatibility.Reason)"
            }
        }
    } else {
        Write-Host "vMotion is not enabled on Host $($host.Name)"
    }
}

# Disconnect from vCenter Server
Disconnect-VIServer -Server $vCenterServerName -Confirm:$false

Stop-Transcript

Not sure what I am doing wrong but its not working. the "foreach ($host in $hosts)" throws a write only error. If anyone could help I would really appreciate it.

I am hoping to use this script to check vMotion compliance and be able to export it to CSV for the managers.

1

There are 1 best solutions below

0
stackprotector On

$host is an already existing, automatic variable in PowerShell. Don't write to it!

To solve your problem, just refactor $host to another name, like $esxi_host.