Using PowerCLI to Detach Luns

Share on:

I thought I would share this script, its been circulating a bit but I feel it is a nice one to have in your toolkit.

Have you ever had to remove a LUN from a cluster and thought “Do I really need to detach all the LUN’s, before un-mapping from my SAN?”

  1. Unmount Datastore
  2. Detach LUN
  3. Un-map from SAN
  4. Rescan Cluster

Well here is a handy script with output. All you need to do is unmount your datastore(s), and then enter in your naaid of your LUN’s and the cluster you want to remove it from, save it an execute. All the LUN’s will be detached without having to manually go and detach it from every LUN in your cluster.

The code and Github Link can be found below.

Detach-ScsiLun.ps1

 1# PowerCLI Script for detaching luns from a cluster
 2# @davidstamen
 3# http://davidstamen.com
 4
 5$LunIDs = "naa.6000000001","naa.600000002"
 6$Clustername = "MyCluster"
 7
 8function Detach-Disk {
 9    param(
10        [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl]$VMHost,
11        [string]$CanonicalName    )
12
13    $storSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem
14    $lunUuid = (Get-ScsiLun -VmHost $VMHost | where {$_.CanonicalName -eq $CanonicalName}).ExtensionData.Uuid
15
16    $storSys.DetachScsiLun($lunUuid)
17}
18
19$ClusterHosts = Get-Cluster $Clustername | Get-VMHost
20
21Foreach($VMHost in $ClusterHosts)
22{
23    Foreach($LUNid in $LunIDs)
24    {
25        Write-Host "Detaching" $LUNid "from" $VMHost -ForegroundColor "Yellow"
26        Detach-Disk -VMHost $VMHost -CanonicalName $LUNid
27    }
28}
29
comments powered by Disqus

See Also