How to get table columns with datatypes (and lengths) using PowerShell?












2















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:SQLMYCOMPUTERMYSQLINSTANCEDatabasesMYDATABASETables' |
Where-Object {$_.DisplayName -match "dbo.MYTABLE"} |
ForEach-Object {$_.Columns} |
Select-Object Name, DataType
$colNames


How to get also datatype lengths for columns?










share|improve this question













migrated from stackoverflow.com Oct 3 '11 at 11:36


This question came from our site for professional and enthusiast programmers.























    2















    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:SQLMYCOMPUTERMYSQLINSTANCEDatabasesMYDATABASETables' |
    Where-Object {$_.DisplayName -match "dbo.MYTABLE"} |
    ForEach-Object {$_.Columns} |
    Select-Object Name, DataType
    $colNames


    How to get also datatype lengths for columns?










    share|improve this question













    migrated from stackoverflow.com Oct 3 '11 at 11:36


    This question came from our site for professional and enthusiast programmers.





















      2












      2








      2


      3






      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:SQLMYCOMPUTERMYSQLINSTANCEDatabasesMYDATABASETables' |
      Where-Object {$_.DisplayName -match "dbo.MYTABLE"} |
      ForEach-Object {$_.Columns} |
      Select-Object Name, DataType
      $colNames


      How to get also datatype lengths for columns?










      share|improve this question














      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:SQLMYCOMPUTERMYSQLINSTANCEDatabasesMYDATABASETables' |
      Where-Object {$_.DisplayName -match "dbo.MYTABLE"} |
      ForEach-Object {$_.Columns} |
      Select-Object Name, DataType
      $colNames


      How to get also datatype lengths for columns?







      sql-server sql-server-2008 powershell






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Sep 30 '11 at 13:04









      jrarajrara

      2,363174862




      2,363174862




      migrated from stackoverflow.com Oct 3 '11 at 11:36


      This question came from our site for professional and enthusiast programmers.









      migrated from stackoverflow.com Oct 3 '11 at 11:36


      This question came from our site for professional and enthusiast programmers.
























          3 Answers
          3






          active

          oldest

          votes


















          5














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



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





          share|improve this answer































            3














            Unfortunately, I don't know the PowerShell syntax, but, heres the SQL for what you want:



            SELECT 
            TableName = OBJECT_NAME(c.OBJECT_ID),
            ColumnName = c.name,
            DataType = t.name, -- Type is an int in the columns table, this returns the type name.
            MaxLength = c.max_length -- Returns the max length of the column.
            FROM
            sys.columns AS c
            JOIN
            sys.types AS t
            ON c.user_type_id=t.user_type_id
            WHERE
            OBJECT_NAME(c.OBJECT_ID) = 'MYTABLE'





            share|improve this answer

































              1














              Thanks to DirtyPaws.
              SQL Statement with Powershell Syntax:



              #Credentials
              $SQLServer = "SQL ServerName/IP Address"
              $SQLDBName = "DatabaseName"
              $uid ="MySqlUser"
              $pwd = "MySqlUserPassword"

              #Establish SQL Connection
              $connectionString = "Server=$SQLServer;Database = $SQLDBName; User ID = $uid; Password = $pwd;"

              $connection = New-Object System.Data.SqlClient.SqlConnection
              $connection.ConnectionString = $connectionString
              $connection.Open()

              #Create SQL Statement
              $query = "
              SELECT
              TableName = OBJECT_NAME(c.OBJECT_ID),
              ColumnName = c.name,
              DataType = t.name, -- Type is an int in the columns table, this returns the type name.
              MaxLength = c.max_length -- Returns the max length of the column.
              FROM
              sys.columns AS c
              JOIN
              sys.types AS t
              ON c.user_type_id=t.user_type_id
              WHERE
              OBJECT_NAME(c.OBJECT_ID) = 'MyTableName'
              "

              #Add SQL Query to SQL Connection
              $command = $connection.CreateCommand()
              $command.CommandText = $query

              #Execute SQL Query
              $result = $command.ExecuteReader()

              #Add result to DataTable Object and Display it
              $table = new-object “System.Data.DataTable”
              $table.Load($result)

              Write-Host ($table | Format-Table | Out-String)
              Write-Host ($table | Format-List | Out-String)





              share|improve this answer

























                Your Answer








                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "182"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: false,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: null,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f6437%2fhow-to-get-table-columns-with-datatypes-and-lengths-using-powershell%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                5














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



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





                share|improve this answer




























                  5














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



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





                  share|improve this answer


























                    5












                    5








                    5







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



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





                    share|improve this answer













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



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






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Sep 30 '11 at 13:37









                    RynantRynant

                    16613




                    16613

























                        3














                        Unfortunately, I don't know the PowerShell syntax, but, heres the SQL for what you want:



                        SELECT 
                        TableName = OBJECT_NAME(c.OBJECT_ID),
                        ColumnName = c.name,
                        DataType = t.name, -- Type is an int in the columns table, this returns the type name.
                        MaxLength = c.max_length -- Returns the max length of the column.
                        FROM
                        sys.columns AS c
                        JOIN
                        sys.types AS t
                        ON c.user_type_id=t.user_type_id
                        WHERE
                        OBJECT_NAME(c.OBJECT_ID) = 'MYTABLE'





                        share|improve this answer






























                          3














                          Unfortunately, I don't know the PowerShell syntax, but, heres the SQL for what you want:



                          SELECT 
                          TableName = OBJECT_NAME(c.OBJECT_ID),
                          ColumnName = c.name,
                          DataType = t.name, -- Type is an int in the columns table, this returns the type name.
                          MaxLength = c.max_length -- Returns the max length of the column.
                          FROM
                          sys.columns AS c
                          JOIN
                          sys.types AS t
                          ON c.user_type_id=t.user_type_id
                          WHERE
                          OBJECT_NAME(c.OBJECT_ID) = 'MYTABLE'





                          share|improve this answer




























                            3












                            3








                            3







                            Unfortunately, I don't know the PowerShell syntax, but, heres the SQL for what you want:



                            SELECT 
                            TableName = OBJECT_NAME(c.OBJECT_ID),
                            ColumnName = c.name,
                            DataType = t.name, -- Type is an int in the columns table, this returns the type name.
                            MaxLength = c.max_length -- Returns the max length of the column.
                            FROM
                            sys.columns AS c
                            JOIN
                            sys.types AS t
                            ON c.user_type_id=t.user_type_id
                            WHERE
                            OBJECT_NAME(c.OBJECT_ID) = 'MYTABLE'





                            share|improve this answer















                            Unfortunately, I don't know the PowerShell syntax, but, heres the SQL for what you want:



                            SELECT 
                            TableName = OBJECT_NAME(c.OBJECT_ID),
                            ColumnName = c.name,
                            DataType = t.name, -- Type is an int in the columns table, this returns the type name.
                            MaxLength = c.max_length -- Returns the max length of the column.
                            FROM
                            sys.columns AS c
                            JOIN
                            sys.types AS t
                            ON c.user_type_id=t.user_type_id
                            WHERE
                            OBJECT_NAME(c.OBJECT_ID) = 'MYTABLE'






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited 3 mins ago









                            John Baughman

                            1051




                            1051










                            answered Sep 30 '11 at 13:18







                            DirtyPaws






























                                1














                                Thanks to DirtyPaws.
                                SQL Statement with Powershell Syntax:



                                #Credentials
                                $SQLServer = "SQL ServerName/IP Address"
                                $SQLDBName = "DatabaseName"
                                $uid ="MySqlUser"
                                $pwd = "MySqlUserPassword"

                                #Establish SQL Connection
                                $connectionString = "Server=$SQLServer;Database = $SQLDBName; User ID = $uid; Password = $pwd;"

                                $connection = New-Object System.Data.SqlClient.SqlConnection
                                $connection.ConnectionString = $connectionString
                                $connection.Open()

                                #Create SQL Statement
                                $query = "
                                SELECT
                                TableName = OBJECT_NAME(c.OBJECT_ID),
                                ColumnName = c.name,
                                DataType = t.name, -- Type is an int in the columns table, this returns the type name.
                                MaxLength = c.max_length -- Returns the max length of the column.
                                FROM
                                sys.columns AS c
                                JOIN
                                sys.types AS t
                                ON c.user_type_id=t.user_type_id
                                WHERE
                                OBJECT_NAME(c.OBJECT_ID) = 'MyTableName'
                                "

                                #Add SQL Query to SQL Connection
                                $command = $connection.CreateCommand()
                                $command.CommandText = $query

                                #Execute SQL Query
                                $result = $command.ExecuteReader()

                                #Add result to DataTable Object and Display it
                                $table = new-object “System.Data.DataTable”
                                $table.Load($result)

                                Write-Host ($table | Format-Table | Out-String)
                                Write-Host ($table | Format-List | Out-String)





                                share|improve this answer






























                                  1














                                  Thanks to DirtyPaws.
                                  SQL Statement with Powershell Syntax:



                                  #Credentials
                                  $SQLServer = "SQL ServerName/IP Address"
                                  $SQLDBName = "DatabaseName"
                                  $uid ="MySqlUser"
                                  $pwd = "MySqlUserPassword"

                                  #Establish SQL Connection
                                  $connectionString = "Server=$SQLServer;Database = $SQLDBName; User ID = $uid; Password = $pwd;"

                                  $connection = New-Object System.Data.SqlClient.SqlConnection
                                  $connection.ConnectionString = $connectionString
                                  $connection.Open()

                                  #Create SQL Statement
                                  $query = "
                                  SELECT
                                  TableName = OBJECT_NAME(c.OBJECT_ID),
                                  ColumnName = c.name,
                                  DataType = t.name, -- Type is an int in the columns table, this returns the type name.
                                  MaxLength = c.max_length -- Returns the max length of the column.
                                  FROM
                                  sys.columns AS c
                                  JOIN
                                  sys.types AS t
                                  ON c.user_type_id=t.user_type_id
                                  WHERE
                                  OBJECT_NAME(c.OBJECT_ID) = 'MyTableName'
                                  "

                                  #Add SQL Query to SQL Connection
                                  $command = $connection.CreateCommand()
                                  $command.CommandText = $query

                                  #Execute SQL Query
                                  $result = $command.ExecuteReader()

                                  #Add result to DataTable Object and Display it
                                  $table = new-object “System.Data.DataTable”
                                  $table.Load($result)

                                  Write-Host ($table | Format-Table | Out-String)
                                  Write-Host ($table | Format-List | Out-String)





                                  share|improve this answer




























                                    1












                                    1








                                    1







                                    Thanks to DirtyPaws.
                                    SQL Statement with Powershell Syntax:



                                    #Credentials
                                    $SQLServer = "SQL ServerName/IP Address"
                                    $SQLDBName = "DatabaseName"
                                    $uid ="MySqlUser"
                                    $pwd = "MySqlUserPassword"

                                    #Establish SQL Connection
                                    $connectionString = "Server=$SQLServer;Database = $SQLDBName; User ID = $uid; Password = $pwd;"

                                    $connection = New-Object System.Data.SqlClient.SqlConnection
                                    $connection.ConnectionString = $connectionString
                                    $connection.Open()

                                    #Create SQL Statement
                                    $query = "
                                    SELECT
                                    TableName = OBJECT_NAME(c.OBJECT_ID),
                                    ColumnName = c.name,
                                    DataType = t.name, -- Type is an int in the columns table, this returns the type name.
                                    MaxLength = c.max_length -- Returns the max length of the column.
                                    FROM
                                    sys.columns AS c
                                    JOIN
                                    sys.types AS t
                                    ON c.user_type_id=t.user_type_id
                                    WHERE
                                    OBJECT_NAME(c.OBJECT_ID) = 'MyTableName'
                                    "

                                    #Add SQL Query to SQL Connection
                                    $command = $connection.CreateCommand()
                                    $command.CommandText = $query

                                    #Execute SQL Query
                                    $result = $command.ExecuteReader()

                                    #Add result to DataTable Object and Display it
                                    $table = new-object “System.Data.DataTable”
                                    $table.Load($result)

                                    Write-Host ($table | Format-Table | Out-String)
                                    Write-Host ($table | Format-List | Out-String)





                                    share|improve this answer















                                    Thanks to DirtyPaws.
                                    SQL Statement with Powershell Syntax:



                                    #Credentials
                                    $SQLServer = "SQL ServerName/IP Address"
                                    $SQLDBName = "DatabaseName"
                                    $uid ="MySqlUser"
                                    $pwd = "MySqlUserPassword"

                                    #Establish SQL Connection
                                    $connectionString = "Server=$SQLServer;Database = $SQLDBName; User ID = $uid; Password = $pwd;"

                                    $connection = New-Object System.Data.SqlClient.SqlConnection
                                    $connection.ConnectionString = $connectionString
                                    $connection.Open()

                                    #Create SQL Statement
                                    $query = "
                                    SELECT
                                    TableName = OBJECT_NAME(c.OBJECT_ID),
                                    ColumnName = c.name,
                                    DataType = t.name, -- Type is an int in the columns table, this returns the type name.
                                    MaxLength = c.max_length -- Returns the max length of the column.
                                    FROM
                                    sys.columns AS c
                                    JOIN
                                    sys.types AS t
                                    ON c.user_type_id=t.user_type_id
                                    WHERE
                                    OBJECT_NAME(c.OBJECT_ID) = 'MyTableName'
                                    "

                                    #Add SQL Query to SQL Connection
                                    $command = $connection.CreateCommand()
                                    $command.CommandText = $query

                                    #Execute SQL Query
                                    $result = $command.ExecuteReader()

                                    #Add result to DataTable Object and Display it
                                    $table = new-object “System.Data.DataTable”
                                    $table.Load($result)

                                    Write-Host ($table | Format-Table | Out-String)
                                    Write-Host ($table | Format-List | Out-String)






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited 3 mins ago









                                    John Baughman

                                    1051




                                    1051










                                    answered Jan 28 '16 at 11:11









                                    Jonathan H.Jonathan H.

                                    1112




                                    1112






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Database Administrators Stack Exchange!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f6437%2fhow-to-get-table-columns-with-datatypes-and-lengths-using-powershell%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        الفوسفات في المغرب

                                        Four equal circles intersect: What is the area of the small shaded portion and its height

                                        بطل الاتحاد السوفيتي