Comment

I tried the script and got a problem/interrogation : only the first lun (extent) of a DataStore is checked by Get-DataStoreMountInfo and detached by Detach-Datastore :

     $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].diskname

By using something like

     $hostviewDSDiskNames = $ds | %{ $_.ExtensionData.Info.vmfs.extent | %{$_.DiskName} }

instead and modifying the equality test for devices :

     #if ($device.canonicalName -eq $hostviewDSDiskName) {    

to something like :

     if ($hostviewDSDiskNames -contains $device.canonicalName) {

ie. testing if the current device is one of the extents forming the DataStore, shouldn't it work better ?

If having serveral LUN in a DS, may it explain  getting StorageConnectivityAlarm ?