Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By : Donabel Santos
Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By: Donabel Santos

Overview of this book

Table of Contents (21 chapters)
SQL Server 2014 with PowerShell v5 Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Reorganizing/rebuilding an index


This recipe demonstrates how to reorganize or rebuild an index.

Getting ready

We will iterate through all the indexes in the Person.Person table in the AdventureWorks2014 database for this exercise.

How to do it...

Let's see how to reorganize or rebuild indexes programmatically:

  1. Open PowerShell ISE as administrator.

  2. Import the SQLPS module and create a new SMO Server object:

    #import SQL Server module
    Import-Module SQLPS -DisableNameChecking
    
    #replace this with your instance name
    $instanceName = "localhost"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName

    Add the following script and run:

    $VerbosePreference = "Continue"
    
    $databasename = "AdventureWorks2014"
    $database = $server.Databases[$databasename]
    
    $tableName = "Person"
    $schemaName = "Person"
    
    $table = $database.Tables |
             Where-Object Schema -like $schemaName |
             Where-Object Name -like $tableName
    
    #From MSDN:
    #EnumFragmentation enumerates a list...