edegrave
Contributor
Contributor

Add functions to detach device script

Jump to solution

I found this script online and it works like a charm. I'm using it to detach devices before storage removes the luns on a vSphere 5 environment (prevent host lock-up by all paths down). In guest iSCSI are presented to the cluster so I can use vRDM to convert them to vmdk. One thing I would like to add, but can't get done, is writing the output to a file (preferably a .cvs) so I can save the work. Additionally (but this is a would be nice to have) instead of reporting an error when a detach is not possible (because it has already been detached manually) I would like to know if it's state was detached or that the device wasn't found on the host. This is the script:

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)

}

$hostslist = import-csv HostList.csv

$luns = import-csv LunList.csv

foreach ($vmhost in $hostslist){

$hostname=$vmhost.host

write-host “Starting $hostname”

$esx = get-vmhost $hostname

foreach ($lun in $luns){

$naa=$lun.naa

write-host “Detaching LUN $naa from $esx”

detach-disk -vmhost $esx -CanonicalName $naa

write-host “Detach Complete”

}

}

Any help very welcome!

Regards

1 Solution

Accepted Solutions
LucD
Leadership
Leadership

Try like this

I added a function Get-DiskState to determine the LUN status.

The result is stored in an object, which is added to an array ($report)

The content of $report is saved in a CSV file

function Detach-Disk{

    param(

    [VMware.VimAutomation.ViCore.Types.V1.Inventory.VMHost]$VMHost,

    [string]$CanonicalName

    )

    

    $storSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem

    $lunUuid = (Get-ScsiLun -VmHost $VMHost | where {$_.CanonicalName -eq $CanonicalName}).ExtensionData.Uuid

    

    $storSys.DetachScsiLun($lunUuid)

}

function Get-DiskState

{

    param(

    [VMware.VimAutomation.ViCore.Types.V1.Inventory.VMHost]$VMHost,

    [string]$CanonicalName

    )

    $storSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem

    $lun = Get-ScsiLun -CanonicalName $CanonicalName -VmHost $VMHost -ErrorAction SilentlyContinue

    if(!$lun){'detached'}

    else{'attached'}

}

$hostslist = import-csv HostList.csv

$luns = import-csv LunList.csv

$report = @()

foreach ($vmhost in $hostslist){

    $hostname=$vmhost.host

    write-host “Starting $hostname

    $esx = get-vmhost $hostname

    foreach ($lun in $luns){

        $naa=$lun.naa

        $lunState = Get-DiskState -VMHost $esx -CanonicalName $naa

        write-host “Detaching LUN $naa from $esx

        if($lunState -eq 'attached'){

            Detach-Disk -vmhost $esx -CanonicalName $naa

        }

        $report += New-Object PSObject -Property @{

            VMHost = $esx.Name

            LUN = $naa

            PreState = $lunState

        }

    }

}

$report | Export-Csv lunreport.csv -NoTypeInformation -UseCulture


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

19 Replies
LucD
Leadership
Leadership

Try like this

I added a function Get-DiskState to determine the LUN status.

The result is stored in an object, which is added to an array ($report)

The content of $report is saved in a CSV file

function Detach-Disk{

    param(

    [VMware.VimAutomation.ViCore.Types.V1.Inventory.VMHost]$VMHost,

    [string]$CanonicalName

    )

    

    $storSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem

    $lunUuid = (Get-ScsiLun -VmHost $VMHost | where {$_.CanonicalName -eq $CanonicalName}).ExtensionData.Uuid

    

    $storSys.DetachScsiLun($lunUuid)

}

function Get-DiskState

{

    param(

    [VMware.VimAutomation.ViCore.Types.V1.Inventory.VMHost]$VMHost,

    [string]$CanonicalName

    )

    $storSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem

    $lun = Get-ScsiLun -CanonicalName $CanonicalName -VmHost $VMHost -ErrorAction SilentlyContinue

    if(!$lun){'detached'}

    else{'attached'}

}

$hostslist = import-csv HostList.csv

$luns = import-csv LunList.csv

$report = @()

foreach ($vmhost in $hostslist){

    $hostname=$vmhost.host

    write-host “Starting $hostname

    $esx = get-vmhost $hostname

    foreach ($lun in $luns){

        $naa=$lun.naa

        $lunState = Get-DiskState -VMHost $esx -CanonicalName $naa

        write-host “Detaching LUN $naa from $esx

        if($lunState -eq 'attached'){

            Detach-Disk -vmhost $esx -CanonicalName $naa

        }

        $report += New-Object PSObject -Property @{

            VMHost = $esx.Name

            LUN = $naa

            PreState = $lunState

        }

    }

}

$report | Export-Csv lunreport.csv -NoTypeInformation -UseCulture


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

edegrave
Contributor
Contributor

That is one really fast answer! Thanks! I must be doing something wrong but getting:

PowerCLI C:\Scripts> .\Detach2.ps1

At C:\Scripts\Detach2.ps1:79 char:38

+         if(($lunState -eq 'attached'){

+                                      ~

Unexpected token '{' in expression or statement.

At C:\Scripts\Detach2.ps1:79 char:38

+         if(($lunState -eq 'attached'){

+                                      ~

Missing closing ')' after expression in 'if' statement.

    + CategoryInfo          : ParserError: (:) [], ParseException

    + FullyQualifiedErrorId : UnexpectedToken

Regards

0 Kudos
LucD
Leadership
Leadership

No, that was me, typo.

Should be corrected now


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

edegrave
Contributor
Contributor

Reading error messages is not that hard. Sorry for being a complete nutter 😉

I've tested with 4 lun's mounted on my lab servers. Detached 1 from host labserver-01. This is the output in the console:

PowerCLI C:\Scripts> .\Detach2.ps1

Starting Labserver-01.vkumo.local

Detaching LUN naa.6001405117de583dcee4d40f9db877d8 from labserver-01.vkumo.local

Detaching LUN naa.60014050b3f2f7ad0cecd4b16d81a6df from labserver-01.vkumo.local

Detaching LUN naa.600140515960792db9c9d46dcd8c4fd2 from labserver-01.vkumo.local

Detaching LUN naa.6001405e4fa0bc3dbf61d4d15d9d07de from labserver-01.vkumo.local

Exception calling "DetachScsiLun" with "1" argument(s): "The operation is not

allowed in the current state."

At C:\Scripts\Detach2.ps1:19 char:5

+     $storSys.DetachScsiLun($lunUuid)

+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

    + FullyQualifiedErrorId : VimException

Starting Labserver-02.vkumo.local

Detaching LUN naa.6001405117de583dcee4d40f9db877d8 from labserver-02.vkumo.local

Detaching LUN naa.60014050b3f2f7ad0cecd4b16d81a6df from labserver-02.vkumo.local

Detaching LUN naa.600140515960792db9c9d46dcd8c4fd2 from labserver-02.vkumo.local

Detaching LUN naa.6001405e4fa0bc3dbf61d4d15d9d07de from labserver-02.vkumo.local

Starting Labserver-03.vkumo.local

Detaching LUN naa.6001405117de583dcee4d40f9db877d8 from labserver-03.vkumo.local

Detaching LUN naa.60014050b3f2f7ad0cecd4b16d81a6df from labserver-03.vkumo.local

Detaching LUN naa.600140515960792db9c9d46dcd8c4fd2 from labserver-03.vkumo.local

Detaching LUN naa.6001405e4fa0bc3dbf61d4d15d9d07de from labserver-03.vkumo.local

So labserver-01 is reporting error as expected. The output in the csv though:

"LUN","PreState","VMHost"

"naa.6001405117de583dcee4d40f9db877d8","attached","labserver-01.vkumo.local"

"naa.60014050b3f2f7ad0cecd4b16d81a6df","detached","labserver-01.vkumo.local"

"naa.600140515960792db9c9d46dcd8c4fd2","attached","labserver-01.vkumo.local"

"naa.6001405e4fa0bc3dbf61d4d15d9d07de","attached","labserver-01.vkumo.local"

"naa.6001405117de583dcee4d40f9db877d8","attached","labserver-02.vkumo.local"

"naa.60014050b3f2f7ad0cecd4b16d81a6df","detached","labserver-02.vkumo.local"

"naa.600140515960792db9c9d46dcd8c4fd2","attached","labserver-02.vkumo.local"

"naa.6001405e4fa0bc3dbf61d4d15d9d07de","attached","labserver-02.vkumo.local"

"naa.6001405117de583dcee4d40f9db877d8","attached","labserver-03.vkumo.local"

"naa.60014050b3f2f7ad0cecd4b16d81a6df","detached","labserver-03.vkumo.local"

"naa.600140515960792db9c9d46dcd8c4fd2","attached","labserver-03.vkumo.local"

"naa.6001405e4fa0bc3dbf61d4d15d9d07de","attached","labserver-03.vkumo.local"

Reporting as it should! Thanks a million!!!! Running it in production tomorrow. Saves me sooo much work!

Regards

0 Kudos
LucD
Leadership
Leadership

Not sure why you get the error on that one LUN.

What state is it in?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
edegrave
Contributor
Contributor

The LUN is detached manually from the host before running the script. Status therefore is 'unmounted' at devices.  The output is only in the console so no problem since the .csv is giving the actual state, which is detached and correct.

Seeing an error is not a problem, just reminds me to double check before letting the storage guys remove the LUN. Output in the file explains the status so I'm all happy!

Thanks!

0 Kudos
edegrave
Contributor
Contributor

Running the script in production now. Works fine, only the error can be a bit of a pain. The status on the iSCSI device is either (operational state) unmounted or mounted (or not present on that specific host in the cluster). Since quite some hosts have LUNs already detached by hand I wanted to make sure by still running the script with the batch of LUNs against the cluster. If the device is mounted the script quickly unmounts it and reports that in the log. If the device is already unmounted by hand, this error shows in recent tasks: The operation is not allowed in the current state. Which makes sense since a unmounted device can't be detached again. Would it be possible to have the script not try to detach the device if it finds that the device is already unmounted or not connected to the server at all? If a LUN is already unmounted it takes the script about 1,5 minutes to continue to the next one. With 30 hosts in this cluster and about 35 luns to detach per batch it takes a long time if any LUNs are already unmounted by hand.

The problem will solve itself in a way since no more LUNs will be detached by hand from now. In a couple of days the script will only find mounted LUNs to detach or not find the device at all (which seems no problem for the script, it just moves. Reports the PreState as detached in the final log). So if it is a lot of work don't bother, but it would make the script run a lot smoother if it could be fixed.

Thanks again!

0 Kudos
kirtyakshay
Contributor
Contributor

I tried to use this script but getting the below error :

pastedImage_2.png

Any suggestion ?

Regards,

Akshay

0 Kudos
LucD
Leadership
Leadership

Looks like the CSV files you are using are not correct


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
kirtyakshay
Contributor
Contributor

I have tried with all the 3 options but still not working.

pastedImage_1.png

The hosts and RDM csv files looks like this :

pastedImage_0.png

Akshay

0 Kudos
kirtyakshay
Contributor
Contributor

I even tried the below script :

pastedImage_0.png

But then I get this :

pastedImage_1.png

Though I can see all the devices on the host:

pastedImage_0.png

Please have a look and suggest

Akshay Kirty

0 Kudos
LucD
Leadership
Leadership

Your CSV has no column names.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
kirtyakshay
Contributor
Contributor

I added the column names both on RDM and the Host file, still the same.

0 Kudos
LucD
Leadership
Leadership

It looks as if the canonical names you are using are not complete.

They seem to be missing the 'naa.' part


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
kirtyakshay
Contributor
Contributor

I have it, see

pastedImage_0.png

0 Kudos
LucD
Leadership
Leadership

I was referring to your inline trial.

And the column headers in your CSVs are wrong.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
kirtyakshay
Contributor
Contributor

I would request to you to help me here.

I have tried all possible options but since I am still learning, I am not able to figure out. Even a screenshot of an example would be really helpful.

Attached are the files that I am trying to use.

0 Kudos
LucD
Leadership
Leadership

In the script, you will see that it expects the column names to be host and naa


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
kirtyakshay
Contributor
Contributor

Worked finally, thanks much.

Akshay Kirty

0 Kudos