Change Column Length via Powershell

Changing the length of a column is not as straightforward as you would think.  There is no .Length property on the smo column object itself, rather you have to set the column.property[‘Length’].value to whatever length you are setting.

[void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")
[void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum")
[void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")

$servers = Get-Content c:\Servers.txt

try{
	$servers | %{
		$srvConn = New-Object "Microsoft.SqlServer.Management.Common.ServerConnection"
		$srvConn.ServerInstance = $_
		$srv = New-Object Microsoft.SqlServer.Management.Smo.Server $srvConn
		
		$srv.databases | where{$_.Status -eq [Microsoft.SqlServer.Management.Smo.DatabaseStatus]::Normal} | %{
			$dbName = $_.Name
			$_.Tables | where{$_.Name -eq "TableName" -and $_.Schema -eq "dbo"} | %{
				$tableName = $_.Name
				$_.Columns | where{$_.Name -eq 'ColumnName'} | %{
					if([int]$_.Properties['Length'].value -eq 100){
						$_.Properties['Length'].value = 500
						$_.Alter();
					}
				}
			}
		}
		
	}
}
catch{
	$_ | fl -Force
}

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 )

Connecting to %s

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