Powershell to dump database schema to text file The Next CEO of Stack Overflowpowershell to...

Does the Brexit deal have to be agreed by both Houses?

What does this shorthand mean?

Removing read access from a file

Implement the Thanos sorting algorithm

Should I tutor a student who I know has cheated on their homework?

How do we know the LHC results are robust?

Why didn't Theresa May consult with Parliament before negotiating a deal with the EU?

Fastest way to shutdown Ubuntu Mate 18.10

Increase performance creating Mandelbrot set in python

Is it okay to store user locations?

Return the Closest Prime Number

Science fiction novels about a solar system spanning civilisation where people change their bodies at will

What can we do to stop prior company from asking us questions?

Why does standard notation not preserve intervals (visually)

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

Why doesn't a table tennis ball float on the surface? How do we calculate buoyancy here?

Can the Reverse Gravity spell affect the Meteor Swarm spell?

What do "high sea" and "carry" mean in this sentence?

What's the point of interval inversion?

Solution of this Diophantine Equation

Rotate a column

Can a caster that cast Polymorph on themselves stop concentrating at any point even if their Int is low?

How to write papers efficiently when English isn't my first language?

Text adventure game code



Powershell to dump database schema to text file



The Next CEO of Stack Overflowpowershell to connect to SQL and display a friendly message when it cannot connectIn Powershell Retrieving Printed Message From SSMSSql Server: how to validate schema against a textual representation (XML or the like) natively?Powershell Error Handling W/ SQL Restore JobsScript file execution through Power shellImprove Restore SpeedDump Oracle database into a textual SQL scriptDump specific tables from DB2 databaseRestore Latest Copy of Full and Differential database From Azure Blob ContainerRunning Powershell Code embedded in SSIS or TSQL, not in external file












1















I want to be able to dump a database schema to a sql text file using Powershell. I want this because our DBAs want to be able to do a diff on the file that is committed to SVN. They won't execute it if they can't see what it contains.



I've found many scripts that backup to a binary .bak file, but I can't find any that dump as a sql text file.



How do you do this in Powershell?










share|improve this question
















bumped to the homepage by Community 4 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.











  • 5





    This looks like what you're looking for: blogs.technet.com/b/heyscriptingguy/archive/2010/11/04/…

    – Thomas Stringer
    Dec 26 '12 at 19:08











  • What are you looking to dump? Data, schema, objects? Yes, no, all?

    – billinkc
    Dec 27 '12 at 18:10











  • @billinkc I would like to dump all but the data.

    – user16527
    Dec 28 '12 at 17:53






  • 1





    In essence, you'd like to mimic the functionality that is available through SSMS wherein you right-click on a databases, Tasks, Generate Scripts and then script all? It would seem the linked article by @sqlvariant/aaron nelson's is exactly what you're looking for. Is there something it does that doesn't satisfy your needs?

    – billinkc
    Dec 28 '12 at 17:57
















1















I want to be able to dump a database schema to a sql text file using Powershell. I want this because our DBAs want to be able to do a diff on the file that is committed to SVN. They won't execute it if they can't see what it contains.



I've found many scripts that backup to a binary .bak file, but I can't find any that dump as a sql text file.



How do you do this in Powershell?










share|improve this question
















bumped to the homepage by Community 4 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.











  • 5





    This looks like what you're looking for: blogs.technet.com/b/heyscriptingguy/archive/2010/11/04/…

    – Thomas Stringer
    Dec 26 '12 at 19:08











  • What are you looking to dump? Data, schema, objects? Yes, no, all?

    – billinkc
    Dec 27 '12 at 18:10











  • @billinkc I would like to dump all but the data.

    – user16527
    Dec 28 '12 at 17:53






  • 1





    In essence, you'd like to mimic the functionality that is available through SSMS wherein you right-click on a databases, Tasks, Generate Scripts and then script all? It would seem the linked article by @sqlvariant/aaron nelson's is exactly what you're looking for. Is there something it does that doesn't satisfy your needs?

    – billinkc
    Dec 28 '12 at 17:57














1












1








1








I want to be able to dump a database schema to a sql text file using Powershell. I want this because our DBAs want to be able to do a diff on the file that is committed to SVN. They won't execute it if they can't see what it contains.



I've found many scripts that backup to a binary .bak file, but I can't find any that dump as a sql text file.



How do you do this in Powershell?










share|improve this question
















I want to be able to dump a database schema to a sql text file using Powershell. I want this because our DBAs want to be able to do a diff on the file that is committed to SVN. They won't execute it if they can't see what it contains.



I've found many scripts that backup to a binary .bak file, but I can't find any that dump as a sql text file.



How do you do this in Powershell?







sql-server schema dump powershell






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 18 '13 at 17:07









Nick Chammas

10.9k1663110




10.9k1663110










asked Dec 26 '12 at 19:03







user16527












bumped to the homepage by Community 4 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 4 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.










  • 5





    This looks like what you're looking for: blogs.technet.com/b/heyscriptingguy/archive/2010/11/04/…

    – Thomas Stringer
    Dec 26 '12 at 19:08











  • What are you looking to dump? Data, schema, objects? Yes, no, all?

    – billinkc
    Dec 27 '12 at 18:10











  • @billinkc I would like to dump all but the data.

    – user16527
    Dec 28 '12 at 17:53






  • 1





    In essence, you'd like to mimic the functionality that is available through SSMS wherein you right-click on a databases, Tasks, Generate Scripts and then script all? It would seem the linked article by @sqlvariant/aaron nelson's is exactly what you're looking for. Is there something it does that doesn't satisfy your needs?

    – billinkc
    Dec 28 '12 at 17:57














  • 5





    This looks like what you're looking for: blogs.technet.com/b/heyscriptingguy/archive/2010/11/04/…

    – Thomas Stringer
    Dec 26 '12 at 19:08











  • What are you looking to dump? Data, schema, objects? Yes, no, all?

    – billinkc
    Dec 27 '12 at 18:10











  • @billinkc I would like to dump all but the data.

    – user16527
    Dec 28 '12 at 17:53






  • 1





    In essence, you'd like to mimic the functionality that is available through SSMS wherein you right-click on a databases, Tasks, Generate Scripts and then script all? It would seem the linked article by @sqlvariant/aaron nelson's is exactly what you're looking for. Is there something it does that doesn't satisfy your needs?

    – billinkc
    Dec 28 '12 at 17:57








5




5





This looks like what you're looking for: blogs.technet.com/b/heyscriptingguy/archive/2010/11/04/…

– Thomas Stringer
Dec 26 '12 at 19:08





This looks like what you're looking for: blogs.technet.com/b/heyscriptingguy/archive/2010/11/04/…

– Thomas Stringer
Dec 26 '12 at 19:08













What are you looking to dump? Data, schema, objects? Yes, no, all?

– billinkc
Dec 27 '12 at 18:10





What are you looking to dump? Data, schema, objects? Yes, no, all?

– billinkc
Dec 27 '12 at 18:10













@billinkc I would like to dump all but the data.

– user16527
Dec 28 '12 at 17:53





@billinkc I would like to dump all but the data.

– user16527
Dec 28 '12 at 17:53




1




1





In essence, you'd like to mimic the functionality that is available through SSMS wherein you right-click on a databases, Tasks, Generate Scripts and then script all? It would seem the linked article by @sqlvariant/aaron nelson's is exactly what you're looking for. Is there something it does that doesn't satisfy your needs?

– billinkc
Dec 28 '12 at 17:57





In essence, you'd like to mimic the functionality that is available through SSMS wherein you right-click on a databases, Tasks, Generate Scripts and then script all? It would seem the linked article by @sqlvariant/aaron nelson's is exactly what you're looking for. Is there something it does that doesn't satisfy your needs?

– billinkc
Dec 28 '12 at 17:57










1 Answer
1






active

oldest

votes


















0














Maybe this could help



https://gist.github.com/cheynewallace/9558179



# Usage:  powershell ExportSchema.ps1 "SERVERNAME" "DATABASE" "C:<YourOutputPath>"


# Start Script
Set-ExecutionPolicy RemoteSigned

# Set-ExecutionPolicy -ExecutionPolicy:Unrestricted -Scope:LocalMachine
function GenerateDBScript([string]$serverName, [string]$dbname, [string]$scriptpath)
{
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.Data") | Out-Null
$srv = new-object "Microsoft.SqlServer.Management.SMO.Server" $serverName
$srv.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject")
$db = New-Object "Microsoft.SqlServer.Management.SMO.Database"
$db = $srv.Databases[$dbname]
$scr = New-Object "Microsoft.SqlServer.Management.Smo.Scripter"
$deptype = New-Object "Microsoft.SqlServer.Management.Smo.DependencyType"
$scr.Server = $srv
$options = New-Object "Microsoft.SqlServer.Management.SMO.ScriptingOptions"
$options.AllowSystemObjects = $false
$options.IncludeDatabaseContext = $true
$options.IncludeIfNotExists = $false
$options.ClusteredIndexes = $true
$options.Default = $true
$options.DriAll = $true
$options.Indexes = $true
$options.NonClusteredIndexes = $true
$options.IncludeHeaders = $false
$options.ToFileOnly = $true
$options.AppendToFile = $true
$options.ScriptDrops = $false

# Set options for SMO.Scripter
$scr.Options = $options

#=============
# Tables
#=============
$options.FileName = $scriptpath + "$($dbname)_tables.sql"
New-Item $options.FileName -type file -force | Out-Null
Foreach ($tb in $db.Tables)
{
If ($tb.IsSystemObject -eq $FALSE)
{
$smoObjects = New-Object Microsoft.SqlServer.Management.Smo.UrnCollection
$smoObjects.Add($tb.Urn)
$scr.Script($smoObjects)
}
}

#=============
# Views
#=============
$options.FileName = $scriptpath + "$($dbname)_views.sql"
New-Item $options.FileName -type file -force | Out-Null
$views = $db.Views | where {$_.IsSystemObject -eq $false}
Foreach ($view in $views)
{
if ($views -ne $null)
{
$scr.Script($view)
}
}

#=============
# StoredProcedures
#=============
$StoredProcedures = $db.StoredProcedures | where {$_.IsSystemObject -eq $false}
$options.FileName = $scriptpath + "$($dbname)_stored_procs.sql"
New-Item $options.FileName -type file -force | Out-Null
Foreach ($StoredProcedure in $StoredProcedures)
{
if ($StoredProcedures -ne $null)
{
$scr.Script($StoredProcedure)
}
}

#=============
# Functions
#=============
$UserDefinedFunctions = $db.UserDefinedFunctions | where {$_.IsSystemObject -eq $false}
$options.FileName = $scriptpath + "$($dbname)_functions.sql"
New-Item $options.FileName -type file -force | Out-Null
Foreach ($function in $UserDefinedFunctions)
{
if ($UserDefinedFunctions -ne $null)
{
$scr.Script($function)
}
}

#=============
# DBTriggers
#=============
$DBTriggers = $db.Triggers
$options.FileName = $scriptpath + "$($dbname)_db_triggers.sql"
New-Item $options.FileName -type file -force | Out-Null
foreach ($trigger in $db.triggers)
{
if ($DBTriggers -ne $null)
{
$scr.Script($DBTriggers)
}
}

#=============
# Table Triggers
#=============
$options.FileName = $scriptpath + "$($dbname)_table_triggers.sql"
New-Item $options.FileName -type file -force | Out-Null
Foreach ($tb in $db.Tables)
{
if($tb.triggers -ne $null)
{
foreach ($trigger in $tb.triggers)
{
$scr.Script($trigger)
}
}
}
}

#=============
# Execute
#=============
GenerateDBScript $args[0] $args[1] $args[2]





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%2f31053%2fpowershell-to-dump-database-schema-to-text-file%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown
























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Maybe this could help



    https://gist.github.com/cheynewallace/9558179



    # Usage:  powershell ExportSchema.ps1 "SERVERNAME" "DATABASE" "C:<YourOutputPath>"


    # Start Script
    Set-ExecutionPolicy RemoteSigned

    # Set-ExecutionPolicy -ExecutionPolicy:Unrestricted -Scope:LocalMachine
    function GenerateDBScript([string]$serverName, [string]$dbname, [string]$scriptpath)
    {
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
    [System.Reflection.Assembly]::LoadWithPartialName("System.Data") | Out-Null
    $srv = new-object "Microsoft.SqlServer.Management.SMO.Server" $serverName
    $srv.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject")
    $db = New-Object "Microsoft.SqlServer.Management.SMO.Database"
    $db = $srv.Databases[$dbname]
    $scr = New-Object "Microsoft.SqlServer.Management.Smo.Scripter"
    $deptype = New-Object "Microsoft.SqlServer.Management.Smo.DependencyType"
    $scr.Server = $srv
    $options = New-Object "Microsoft.SqlServer.Management.SMO.ScriptingOptions"
    $options.AllowSystemObjects = $false
    $options.IncludeDatabaseContext = $true
    $options.IncludeIfNotExists = $false
    $options.ClusteredIndexes = $true
    $options.Default = $true
    $options.DriAll = $true
    $options.Indexes = $true
    $options.NonClusteredIndexes = $true
    $options.IncludeHeaders = $false
    $options.ToFileOnly = $true
    $options.AppendToFile = $true
    $options.ScriptDrops = $false

    # Set options for SMO.Scripter
    $scr.Options = $options

    #=============
    # Tables
    #=============
    $options.FileName = $scriptpath + "$($dbname)_tables.sql"
    New-Item $options.FileName -type file -force | Out-Null
    Foreach ($tb in $db.Tables)
    {
    If ($tb.IsSystemObject -eq $FALSE)
    {
    $smoObjects = New-Object Microsoft.SqlServer.Management.Smo.UrnCollection
    $smoObjects.Add($tb.Urn)
    $scr.Script($smoObjects)
    }
    }

    #=============
    # Views
    #=============
    $options.FileName = $scriptpath + "$($dbname)_views.sql"
    New-Item $options.FileName -type file -force | Out-Null
    $views = $db.Views | where {$_.IsSystemObject -eq $false}
    Foreach ($view in $views)
    {
    if ($views -ne $null)
    {
    $scr.Script($view)
    }
    }

    #=============
    # StoredProcedures
    #=============
    $StoredProcedures = $db.StoredProcedures | where {$_.IsSystemObject -eq $false}
    $options.FileName = $scriptpath + "$($dbname)_stored_procs.sql"
    New-Item $options.FileName -type file -force | Out-Null
    Foreach ($StoredProcedure in $StoredProcedures)
    {
    if ($StoredProcedures -ne $null)
    {
    $scr.Script($StoredProcedure)
    }
    }

    #=============
    # Functions
    #=============
    $UserDefinedFunctions = $db.UserDefinedFunctions | where {$_.IsSystemObject -eq $false}
    $options.FileName = $scriptpath + "$($dbname)_functions.sql"
    New-Item $options.FileName -type file -force | Out-Null
    Foreach ($function in $UserDefinedFunctions)
    {
    if ($UserDefinedFunctions -ne $null)
    {
    $scr.Script($function)
    }
    }

    #=============
    # DBTriggers
    #=============
    $DBTriggers = $db.Triggers
    $options.FileName = $scriptpath + "$($dbname)_db_triggers.sql"
    New-Item $options.FileName -type file -force | Out-Null
    foreach ($trigger in $db.triggers)
    {
    if ($DBTriggers -ne $null)
    {
    $scr.Script($DBTriggers)
    }
    }

    #=============
    # Table Triggers
    #=============
    $options.FileName = $scriptpath + "$($dbname)_table_triggers.sql"
    New-Item $options.FileName -type file -force | Out-Null
    Foreach ($tb in $db.Tables)
    {
    if($tb.triggers -ne $null)
    {
    foreach ($trigger in $tb.triggers)
    {
    $scr.Script($trigger)
    }
    }
    }
    }

    #=============
    # Execute
    #=============
    GenerateDBScript $args[0] $args[1] $args[2]





    share|improve this answer




























      0














      Maybe this could help



      https://gist.github.com/cheynewallace/9558179



      # Usage:  powershell ExportSchema.ps1 "SERVERNAME" "DATABASE" "C:<YourOutputPath>"


      # Start Script
      Set-ExecutionPolicy RemoteSigned

      # Set-ExecutionPolicy -ExecutionPolicy:Unrestricted -Scope:LocalMachine
      function GenerateDBScript([string]$serverName, [string]$dbname, [string]$scriptpath)
      {
      [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
      [System.Reflection.Assembly]::LoadWithPartialName("System.Data") | Out-Null
      $srv = new-object "Microsoft.SqlServer.Management.SMO.Server" $serverName
      $srv.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject")
      $db = New-Object "Microsoft.SqlServer.Management.SMO.Database"
      $db = $srv.Databases[$dbname]
      $scr = New-Object "Microsoft.SqlServer.Management.Smo.Scripter"
      $deptype = New-Object "Microsoft.SqlServer.Management.Smo.DependencyType"
      $scr.Server = $srv
      $options = New-Object "Microsoft.SqlServer.Management.SMO.ScriptingOptions"
      $options.AllowSystemObjects = $false
      $options.IncludeDatabaseContext = $true
      $options.IncludeIfNotExists = $false
      $options.ClusteredIndexes = $true
      $options.Default = $true
      $options.DriAll = $true
      $options.Indexes = $true
      $options.NonClusteredIndexes = $true
      $options.IncludeHeaders = $false
      $options.ToFileOnly = $true
      $options.AppendToFile = $true
      $options.ScriptDrops = $false

      # Set options for SMO.Scripter
      $scr.Options = $options

      #=============
      # Tables
      #=============
      $options.FileName = $scriptpath + "$($dbname)_tables.sql"
      New-Item $options.FileName -type file -force | Out-Null
      Foreach ($tb in $db.Tables)
      {
      If ($tb.IsSystemObject -eq $FALSE)
      {
      $smoObjects = New-Object Microsoft.SqlServer.Management.Smo.UrnCollection
      $smoObjects.Add($tb.Urn)
      $scr.Script($smoObjects)
      }
      }

      #=============
      # Views
      #=============
      $options.FileName = $scriptpath + "$($dbname)_views.sql"
      New-Item $options.FileName -type file -force | Out-Null
      $views = $db.Views | where {$_.IsSystemObject -eq $false}
      Foreach ($view in $views)
      {
      if ($views -ne $null)
      {
      $scr.Script($view)
      }
      }

      #=============
      # StoredProcedures
      #=============
      $StoredProcedures = $db.StoredProcedures | where {$_.IsSystemObject -eq $false}
      $options.FileName = $scriptpath + "$($dbname)_stored_procs.sql"
      New-Item $options.FileName -type file -force | Out-Null
      Foreach ($StoredProcedure in $StoredProcedures)
      {
      if ($StoredProcedures -ne $null)
      {
      $scr.Script($StoredProcedure)
      }
      }

      #=============
      # Functions
      #=============
      $UserDefinedFunctions = $db.UserDefinedFunctions | where {$_.IsSystemObject -eq $false}
      $options.FileName = $scriptpath + "$($dbname)_functions.sql"
      New-Item $options.FileName -type file -force | Out-Null
      Foreach ($function in $UserDefinedFunctions)
      {
      if ($UserDefinedFunctions -ne $null)
      {
      $scr.Script($function)
      }
      }

      #=============
      # DBTriggers
      #=============
      $DBTriggers = $db.Triggers
      $options.FileName = $scriptpath + "$($dbname)_db_triggers.sql"
      New-Item $options.FileName -type file -force | Out-Null
      foreach ($trigger in $db.triggers)
      {
      if ($DBTriggers -ne $null)
      {
      $scr.Script($DBTriggers)
      }
      }

      #=============
      # Table Triggers
      #=============
      $options.FileName = $scriptpath + "$($dbname)_table_triggers.sql"
      New-Item $options.FileName -type file -force | Out-Null
      Foreach ($tb in $db.Tables)
      {
      if($tb.triggers -ne $null)
      {
      foreach ($trigger in $tb.triggers)
      {
      $scr.Script($trigger)
      }
      }
      }
      }

      #=============
      # Execute
      #=============
      GenerateDBScript $args[0] $args[1] $args[2]





      share|improve this answer


























        0












        0








        0







        Maybe this could help



        https://gist.github.com/cheynewallace/9558179



        # Usage:  powershell ExportSchema.ps1 "SERVERNAME" "DATABASE" "C:<YourOutputPath>"


        # Start Script
        Set-ExecutionPolicy RemoteSigned

        # Set-ExecutionPolicy -ExecutionPolicy:Unrestricted -Scope:LocalMachine
        function GenerateDBScript([string]$serverName, [string]$dbname, [string]$scriptpath)
        {
        [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
        [System.Reflection.Assembly]::LoadWithPartialName("System.Data") | Out-Null
        $srv = new-object "Microsoft.SqlServer.Management.SMO.Server" $serverName
        $srv.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject")
        $db = New-Object "Microsoft.SqlServer.Management.SMO.Database"
        $db = $srv.Databases[$dbname]
        $scr = New-Object "Microsoft.SqlServer.Management.Smo.Scripter"
        $deptype = New-Object "Microsoft.SqlServer.Management.Smo.DependencyType"
        $scr.Server = $srv
        $options = New-Object "Microsoft.SqlServer.Management.SMO.ScriptingOptions"
        $options.AllowSystemObjects = $false
        $options.IncludeDatabaseContext = $true
        $options.IncludeIfNotExists = $false
        $options.ClusteredIndexes = $true
        $options.Default = $true
        $options.DriAll = $true
        $options.Indexes = $true
        $options.NonClusteredIndexes = $true
        $options.IncludeHeaders = $false
        $options.ToFileOnly = $true
        $options.AppendToFile = $true
        $options.ScriptDrops = $false

        # Set options for SMO.Scripter
        $scr.Options = $options

        #=============
        # Tables
        #=============
        $options.FileName = $scriptpath + "$($dbname)_tables.sql"
        New-Item $options.FileName -type file -force | Out-Null
        Foreach ($tb in $db.Tables)
        {
        If ($tb.IsSystemObject -eq $FALSE)
        {
        $smoObjects = New-Object Microsoft.SqlServer.Management.Smo.UrnCollection
        $smoObjects.Add($tb.Urn)
        $scr.Script($smoObjects)
        }
        }

        #=============
        # Views
        #=============
        $options.FileName = $scriptpath + "$($dbname)_views.sql"
        New-Item $options.FileName -type file -force | Out-Null
        $views = $db.Views | where {$_.IsSystemObject -eq $false}
        Foreach ($view in $views)
        {
        if ($views -ne $null)
        {
        $scr.Script($view)
        }
        }

        #=============
        # StoredProcedures
        #=============
        $StoredProcedures = $db.StoredProcedures | where {$_.IsSystemObject -eq $false}
        $options.FileName = $scriptpath + "$($dbname)_stored_procs.sql"
        New-Item $options.FileName -type file -force | Out-Null
        Foreach ($StoredProcedure in $StoredProcedures)
        {
        if ($StoredProcedures -ne $null)
        {
        $scr.Script($StoredProcedure)
        }
        }

        #=============
        # Functions
        #=============
        $UserDefinedFunctions = $db.UserDefinedFunctions | where {$_.IsSystemObject -eq $false}
        $options.FileName = $scriptpath + "$($dbname)_functions.sql"
        New-Item $options.FileName -type file -force | Out-Null
        Foreach ($function in $UserDefinedFunctions)
        {
        if ($UserDefinedFunctions -ne $null)
        {
        $scr.Script($function)
        }
        }

        #=============
        # DBTriggers
        #=============
        $DBTriggers = $db.Triggers
        $options.FileName = $scriptpath + "$($dbname)_db_triggers.sql"
        New-Item $options.FileName -type file -force | Out-Null
        foreach ($trigger in $db.triggers)
        {
        if ($DBTriggers -ne $null)
        {
        $scr.Script($DBTriggers)
        }
        }

        #=============
        # Table Triggers
        #=============
        $options.FileName = $scriptpath + "$($dbname)_table_triggers.sql"
        New-Item $options.FileName -type file -force | Out-Null
        Foreach ($tb in $db.Tables)
        {
        if($tb.triggers -ne $null)
        {
        foreach ($trigger in $tb.triggers)
        {
        $scr.Script($trigger)
        }
        }
        }
        }

        #=============
        # Execute
        #=============
        GenerateDBScript $args[0] $args[1] $args[2]





        share|improve this answer













        Maybe this could help



        https://gist.github.com/cheynewallace/9558179



        # Usage:  powershell ExportSchema.ps1 "SERVERNAME" "DATABASE" "C:<YourOutputPath>"


        # Start Script
        Set-ExecutionPolicy RemoteSigned

        # Set-ExecutionPolicy -ExecutionPolicy:Unrestricted -Scope:LocalMachine
        function GenerateDBScript([string]$serverName, [string]$dbname, [string]$scriptpath)
        {
        [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
        [System.Reflection.Assembly]::LoadWithPartialName("System.Data") | Out-Null
        $srv = new-object "Microsoft.SqlServer.Management.SMO.Server" $serverName
        $srv.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject")
        $db = New-Object "Microsoft.SqlServer.Management.SMO.Database"
        $db = $srv.Databases[$dbname]
        $scr = New-Object "Microsoft.SqlServer.Management.Smo.Scripter"
        $deptype = New-Object "Microsoft.SqlServer.Management.Smo.DependencyType"
        $scr.Server = $srv
        $options = New-Object "Microsoft.SqlServer.Management.SMO.ScriptingOptions"
        $options.AllowSystemObjects = $false
        $options.IncludeDatabaseContext = $true
        $options.IncludeIfNotExists = $false
        $options.ClusteredIndexes = $true
        $options.Default = $true
        $options.DriAll = $true
        $options.Indexes = $true
        $options.NonClusteredIndexes = $true
        $options.IncludeHeaders = $false
        $options.ToFileOnly = $true
        $options.AppendToFile = $true
        $options.ScriptDrops = $false

        # Set options for SMO.Scripter
        $scr.Options = $options

        #=============
        # Tables
        #=============
        $options.FileName = $scriptpath + "$($dbname)_tables.sql"
        New-Item $options.FileName -type file -force | Out-Null
        Foreach ($tb in $db.Tables)
        {
        If ($tb.IsSystemObject -eq $FALSE)
        {
        $smoObjects = New-Object Microsoft.SqlServer.Management.Smo.UrnCollection
        $smoObjects.Add($tb.Urn)
        $scr.Script($smoObjects)
        }
        }

        #=============
        # Views
        #=============
        $options.FileName = $scriptpath + "$($dbname)_views.sql"
        New-Item $options.FileName -type file -force | Out-Null
        $views = $db.Views | where {$_.IsSystemObject -eq $false}
        Foreach ($view in $views)
        {
        if ($views -ne $null)
        {
        $scr.Script($view)
        }
        }

        #=============
        # StoredProcedures
        #=============
        $StoredProcedures = $db.StoredProcedures | where {$_.IsSystemObject -eq $false}
        $options.FileName = $scriptpath + "$($dbname)_stored_procs.sql"
        New-Item $options.FileName -type file -force | Out-Null
        Foreach ($StoredProcedure in $StoredProcedures)
        {
        if ($StoredProcedures -ne $null)
        {
        $scr.Script($StoredProcedure)
        }
        }

        #=============
        # Functions
        #=============
        $UserDefinedFunctions = $db.UserDefinedFunctions | where {$_.IsSystemObject -eq $false}
        $options.FileName = $scriptpath + "$($dbname)_functions.sql"
        New-Item $options.FileName -type file -force | Out-Null
        Foreach ($function in $UserDefinedFunctions)
        {
        if ($UserDefinedFunctions -ne $null)
        {
        $scr.Script($function)
        }
        }

        #=============
        # DBTriggers
        #=============
        $DBTriggers = $db.Triggers
        $options.FileName = $scriptpath + "$($dbname)_db_triggers.sql"
        New-Item $options.FileName -type file -force | Out-Null
        foreach ($trigger in $db.triggers)
        {
        if ($DBTriggers -ne $null)
        {
        $scr.Script($DBTriggers)
        }
        }

        #=============
        # Table Triggers
        #=============
        $options.FileName = $scriptpath + "$($dbname)_table_triggers.sql"
        New-Item $options.FileName -type file -force | Out-Null
        Foreach ($tb in $db.Tables)
        {
        if($tb.triggers -ne $null)
        {
        foreach ($trigger in $tb.triggers)
        {
        $scr.Script($trigger)
        }
        }
        }
        }

        #=============
        # Execute
        #=============
        GenerateDBScript $args[0] $args[1] $args[2]






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Feb 16 at 21:45









        AndyDaSilva52AndyDaSilva52

        11




        11






























            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%2f31053%2fpowershell-to-dump-database-schema-to-text-file%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

            ORA-01691 (unable to extend lob segment) even though my tablespace has AUTOEXTEND onORA-01692: unable to...

            Always On Availability groups resolving state after failover - Remote harden of transaction...

            Circunscripción electoral de Guipúzcoa Referencias Menú de navegaciónLas claves del sistema electoral en...