Sql-server – How to get table columns with datatypes (and lengths) using PowerShell

powershellsql serversql-server-2008

I'm trying to get column names with data types (and lengths) for SQL Server instance using PowerShell. I got this far:

#Load PSSnapin
Add-PSSnapin *SQL*

#Get column names
$colNames = dir 'SQLSERVER:\SQL\MYCOMPUTER\MYSQLINSTANCE\Databases\MYDATABASE\Tables' | 
    Where-Object {$_.DisplayName -match "dbo.MYTABLE"} | 
        ForEach-Object {$_.Columns} |
            Select-Object Name, DataType
$colNames

How to get also datatype lengths for columns?

Best Answer

The lengths are found at <Column>.Properties['Length'].Value, so you can select it like:

#Get column names
$colNames = dir 'SQLSERVER:\SQL\MYCOMPUTER\MYSQLINSTANCE\Databases\MYDATABASE\Tables' | 
    Where-Object {$_.DisplayName -match "dbo.MYTABLE"} | 
        ForEach-Object {$_.Columns} |
            Select-Object Name, DataType, `
                @{Name='Length'; Expression = {$_.Properties['Length'].Value}}
$colNames