Detach LUNs from Multiple ESXi Hosts Using Powercli

Hi there

Migrating an old VMWare Vcenter environment to newer vcsa 6.5 can be challenging. In the process I found myself doing other tasks like converting RDMs (Mapped Raw LUN) to .vmdk files.

Migrating RDMs attached to virtual machines on my Vcenter 5.5 environment to .vmdk disk files appeared like a tedious handy task especially when you have these LUNs attached to many ESXi hosts. With the help of powershell and Powercli the task becomes much easier.

I found it comfortable and safer to detach each LUN from all ESXi servers, so this script answers my current need and may be modified as needed. Im aware that it can still be improved and I hope to publish new and improved versions later.

The script asks for the “LUN canonicalName” and performs a Detach action on each Host from the list you provide.

You can find the LUN canonicalName here:LUN canonical name

Prepare a text file with the ESX servers list in c:\temp\esxList.txt, one in each line like so:

esx1.domain.local
esx2.domain.local
esx3.domain.local

Run the script and enter the LUN canonicalName like seen in the above picture.

$CanonicalName = Read-Host "Enter LUN canonicalName"
vcName = "enter vcenter name here"
#get list of hosts
$hostslist = Get-Content "c:\temp\esxList.txt"

# Load VMware PowerShell Module (PowerCLI):
If ((Get-Module VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null)
{
    Import-Module VMware.VimAutomation.Core
}

#check if connected to VC and connect if not
$viserver = $global:defaultviserver.Name
if ($viserver -ne $vcName) {
Connect-VIServer -Server vc55
}

#Start looping ESXi hosts and detach LUNs
foreach ($vmhost in $hostslist){

    write-host “Starting $vmhost”
    $esx = get-vmhost $vmhost
    
        $storSys = Get-View $esx.Extensiondata.ConfigManager.StorageSystem
        $lunUuid = (Get-ScsiLun -VmHost $VMHost | where {$_.CanonicalName -eq $CanonicalName}).ExtensionData.Uuid
        "Detaching $lunUuid"
        $storSys.DetachScsiLun($lunUuid) 
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.