Script Indexes with Powershell

Quick script to script out individual indexes via powershell.

[string]$InstanceName = "InstanceName"
[string]$DBName = "DatabaseName"
[string]$TableName = "TableName"
[string]$FileLocation = "C:\Test\ScriptIDX"
$indexes = "Index1", "Index2", "Index3", "Index4"

$srv = Get-SqlServer -username "UserName" -password "Password" -sqlserver $InstanceName
$Table = Get-SqlTable $(Get-SqlDatabase -sqlserver $srv $DBName) -Name $TableName
foreach($ix in $Table.Indexes | where{$indexes -contains $_.Name })
{
	$ix.Script() | out-file "$FileLocation\$($ix.Name).sql" #-append; "GO`n$($separator)`n" | out-file "$FileLocation\$($Table.Name).sql" -append -Force
}


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.