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
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: