Skip to content

April 2, 2014

Add a column to a table via powershell

by Scott Newman

Quick post on how to add a column to a table via powershell.  I had a need to blast a new column onto a bunch of databases on a bunch of servers.  Powershell makes this too easy.  Use at your own risk. 


$servers = Get-Content c:\Servers.txt
$tableName = 'TableName'
$schema = 'dbo'
$columnName = 'ColumnName'


	$servers | %{
		$srvName = $_
		$srvConn = New-Object "Microsoft.SqlServer.Management.Common.ServerConnection"
		$srvConn.ServerInstance = $srvName
		$srv = New-Object Microsoft.SqlServer.Management.Smo.Server $srvConn

		$srv.Databases | where{$_.Status -eq [Microsoft.SqlServer.Management.Smo.DatabaseStatus]::Normal} | %{
			$dbName = $_.Name
			$table = $_.Tables | where{$_.Name -eq $tableName -and $_.Schema -eq $schema}
			if($table -ne $null){
				$column = $table.Columns | where{$_.Name -eq $columnName}
				if($column -eq $null){  #add the column if it does not exist
					$column = New-Object Microsoft.SqlServer.Management.Smo.Column
					$column.Parent = $table
					$column.Name = $columnName
					$column.DataType = [Microsoft.SqlServer.Management.Smo.DataType]::DateTime


	$_ | fl -Force
Read more from Powershell, SQL Server

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

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

%d bloggers like this: