PowerCLI Unmap Multiple Datastores

binary-1254484_640Here is a script I have that I use quite frequently. There are times I need to run an unmap on my volumes to help free up space that the SAN thinks is still in use. Some of my VCenter Environments contain a lot of Datastores, so it can get very  redundant having to run the command one by one within the putty session. So here is a script that will connect to my VCenter, grab a random Host, and start unmapping each datastore within the wildcard parameter. You can also just do one datastore if you would like by putting the full datastore name instead of using a wildcard. If you have storage DRS enabled on a thin-provisoned back in SAN this will definitely come in handy, and I suggest you make it a scheduled task to run frequently.

So things you will need to change for your environment $VIServer = “vcentername” , -Name Datastore* , -Location ClusterName

# Start Load VMware  Snapin (if not already loaded)
if (!(Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) {
	if (!(Add-PSSnapin -PassThru VMware.VimAutomation.Core)) {
		# Error out if loading fails
		Write-Error "ERROR: Cannot load the VMware Snapin. Is the PowerCLI installed?"
# End Load VMware  Snapin (if not already loaded)

# Start Set Session Timout
$initialTimeout = (Get-PowerCLIConfiguration -Scope Session).WebOperationTimeoutSeconds
Set-PowerCLIConfiguration -Scope Session -WebOperationTimeoutSeconds -1 -Confirm:$False
# End Set Session Timout

# Global Paramenters
$VIServer = "vcentername"
$Verberose = $true

#Connect to VCenter
$OpenConnection = $global:DefaultVIServers | where { $_.Name -eq $VIServer }
if($OpenConnection.IsConnected) {
	Write-Output "vCenter is Already Connected..."
	$VIConnection = $OpenConnection
} else {
Connect-VIServer -Server $VIServer 


foreach ($ds in (Get-Datastore -Name COMP* | where{$_.Type -eq 'VMFS'}))
$esx = Get-VMHost -Location ClusterName -Datastore $ds | Get-Random -Count 1
$esxcli = Get-EsxCli -VMHost $esx
Write-Host 'Unmapping' $ds on $esx
$esxcli.storage.vmfs.unmap($null, $ds.Name, $null)

Write-Host 'Datastore' $ds.Name ' has been unmapped' 
Write-Host 'Completed all Datastore UN-Mappings'
Write-Host 'Disconnecting from VCENTER' $VIServer 

Disconnect-VIServer $VIServer -Confirm:$false


2 Responses to “PowerCLI Unmap Multiple Datastores”

  1. Dorian

    Sep 18. 2017

    Just a quick question on the -WebOperationTimeoutSeconds -1

    What is the logic behind using -1 for this operation.

    Reply to this comment
  2. Prashant M B

    Dec 19. 2016

    I am looking for powercli script to unmap 8 datastores in parallel (at once) with 200MB reclaim unit. could you help me with that?

    Prashant M B

    Reply to this comment

Leave a Reply