Skip to content

Instantly share code, notes, and snippets.

@philipproplesch
Last active December 18, 2015 19:08
Show Gist options
  • Save philipproplesch/5830384 to your computer and use it in GitHub Desktop.
Save philipproplesch/5830384 to your computer and use it in GitHub Desktop.
$serverName = ""
$userName = ""
$password = ""
$maxFragmentation = 10
$databases = @("Dev", "QA", "Stage")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")
$connection = New-Object Microsoft.SqlServer.Management.Common.ServerConnection
$connection.ServerInstance = $serverName
if ($userName -and $password) {
$connection.LoginSecure = $false
$connection.Login = $userName
$connection.Password = $password
}
$server = New-Object Microsoft.SqlServer.Management.Smo.Server($connection)
function RebuildIndexes($databases, $source) {
ForEach ($obj in $source) {
Write-Host "$database -> $obj"
# Iterate over indexes in the given table/view
ForEach ($index in $obj.Indexes) {
$fragmentation = $index.EnumFragmentation() | ForEach-Object {
$_.AverageFragmentation
}
if ($fragmentation -gt $maxFragmentation) {
Write-Host "`t$index ($fragmentation %)" -ForegroundColor Red
$index.Rebuild()
Write-Host "`tThe index has been successfully rebuilded." -ForegroundColor Yellow
}
else {
$index.Reorganize()
$index.UpdateStatistics()
Write-Host "`tThe index has been successfully reorganized." -ForegroundColor Yellow
}
}
}
}
ForEach ($database in $server.Databases) {
if($databases -and $databases -notcontains $database.Name) {
continue;
}
RebuildIndexes $database $database.Tables
RebuildIndexes $database $database.Views
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment