Delete the Elastic search Indexes by using power shell

RamanaReddy V
2 min readNov 5, 2019

--

Most of the cases we can create single index name and reusing them but some cases you want to maintain Versioning for that indexes based on your production releases. So, you want to clean up the ES server based on the created date below power shell script help us to delete automatically all unused ES indexes.

I tested below script on my windows 10 PC without any authentication of ES server.We may PROD ES server required for authentication to access the indexes for that we can use attribute like ‘-Credential & -Headers ‘ in requested URL.

The below script explains the remove unused index’s from Elastic search server based index created date. For Example: If you want to keep only last 3 months of created index’s and delete rest of index’s.

$monthNum=-3
$esServerURL ='http://localhost:9200/'
function GetResponseOfRequest($requestURL,$requestVerb){$fullURL= -join($esServerURL,$requestURL)
$response = Invoke-WebRequest -Uri $fullURL -Method $requestVerb -ContentType 'application/json'
return $response
}
$lastmonth = (Get-Date).AddMonths($monthNum).Date# Step1: Get all index names within month boundary...
$response = GetResponseOfRequest "_cat/indices?h=index,creation.date.string&s=creation.date&format=json" "Get"
if($response.StatusCode -eq 200){
$json= $response.Content | ConvertFrom-Jsonforeach($line in $json){$indexCreatedDate= $line.'creation.date.string'if((Get-Date $indexCreatedDate) -le (Get-Date $lastmonth)){
# Step2: delete the index based on condition...
$delresponse = GetResponseOfRequest $line.index "Delete"
if($response.StatusCode -eq 200){
Write-Output "Success fully deleted index is: " $line.index
}
else{
# throw error
throw "Bad request.......! $delresponse"
}
}
}
}
else{
throw "Bad request.......! $response "
# throw error

}

Some times you may get below exception while running script

Power shell Access Exception

To overcome above error you may set the execution policy like below:

Set-ExecutionPolicy -ExecutionPolicy policyname

Note:

If you have any better suggestion other than this script, please feel free and do a comment so that I can also update myself like you 😄.

--

--

RamanaReddy V
RamanaReddy V

No responses yet