Home > LUN, PowerShell, vSphere > LUN juggling in vSphere 5

LUN juggling in vSphere 5

November 25th, 2011 Leave a comment Go to comments

Buried in the massive amount of new features introduced with vSphere 5 there are several new API methods on the HostStorageSystem managed object.

Two of these API methods will allow you to automate the new Attach/Detach LUN feature from the vSphere Client. It concerns the AttachScsiLun and DetachScsiLun methods. Until this new feature is available natively in PowerCLI, you can use the following functions.

Script

function Attach-Disk{
    param(
        [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl]$VMHost,
        [string]$CanonicalName
    )
    
    $storSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem
    $lunUuid = (Get-ScsiLun -VmHost $VMHost | 
      where {$_.CanonicalName -eq $CanonicalName}).ExtensionData.Uuid
    
    $storSys.AttachScsiLun($lunUuid)
}

function Detach-Disk{
    param(
        [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl]$VMHost,
        [string]$CanonicalName
    )
    
    $storSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem
    $lunUuid = (Get-ScsiLun -VmHost $VMHost | 
      where {$_.CanonicalName -eq $CanonicalName}).ExtensionData.Uuid
    
    $storSys.DetachScsiLun($lunUuid)
}

Annotations

Line 3,16: The host where you want to attach/detach the LUN must be provided as a VMHostImpl object

Line 4,17: The LUN you want to attch/detach is identified with it’s Canonicalname

Line 7,20: The AttachScsiLun and DetachScsiLun methods are present on the StorageSystem Managed Object.

Line 8-9,21-22: Both methods want the UUID of the LUN.

Sample run

A very simple example that shows how you can detach a LUN from a host.

$esx = Get-VMHost MyEsx
$name = "The-canonical-name-of-the-target-LUN"

Detach-Disk -VMHost $esx -CanonicalName $name

There are other new methods on the HostStorageSystem managed object that were introduced in vSphere 5. I’ll handle those in a future post.

Enjoy !

  1. andre
    December 14th, 2012 at 13:34 | #1

    i look for a simple script to mount a vmfs datastore

    vSphere PowerCLI> $CanonicalName = “naa.60a980005034472f544a6f416d4a487a”
    vSphere PowerCLI> Write-Host $CanonicalName
    naa.60a980005034472f544a6f416d4a487a
    vSphere PowerCLI> $esx = Get-VMHost
    vSphere PowerCLI> Write-Host $esx
    ls-esxt-01
    vSphere PowerCLI> Attach-Disk -vmhost $esx -CanonicalName $CanonicalName
    Ausnahme beim Aufrufen von “AttachScsiLun” mit 1 Argument(en): “The operation is not allowed in the current state.”
    Bei Zeile:9 Zeichen:27
    + $storSys.AttachScsiLun <<<< ($lunUuid)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

  1. June 11th, 2013 at 11:21 | #1