title: How to generate sql scripts using SMO scripter
body: <p>My database has tables, views and all. And I need a way to generate SQL script for all the DDL in an automated manner. No need for data.</p>
  
  <p>There are FK constraints so table creation scripts should be ordered properly. Some views use another view, so view creation scripts also have to be ordered properly.</p>
  
  <p>Starting from a script presented on <a href="http://blogs.msdn.com/b/sqlagent/archive/2012/08/28/using-powershell-script-to-script-out-tables-and-procedures-with-dependencies-and-permissions.aspx" rel="noreferrer">MSDN Blog</a>, I got the following:</p>
  
  <pre class="lang-bsh prettyprint-override"><code>function Generate-SqlScript
  {
      param(
      [string]$srvname,
      [string]$database,
      [string]$ScriptOutputFileName
      )
  
      [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
  
      $srv =  New-Object ("Microsoft.SqlServer.Management.SMO.Server") ($srvname)
  
      $allUrns = @()
      $allUrns += $srv.Databases[$database].Tables |  foreach { $_.Urn}
      $allUrns += $srv.Databases[$database].Views |  foreach { $_.Urn}
  
      $scriptingOptions = New-Object ("Microsoft.SqlServer.Management.SMO.ScriptingOptions") 
      $scriptingOptions.WithDependencies = $true
      $scriptingOptions.AllowSystemObjects = $false
      $scriptingOptions.ToFileOnly = $true
      $scriptingOptions.Permissions = $true
      $scriptingOptions.FileName = "$ScriptOutputFileName"
  
      $scripter = New-Object ("Microsoft.SqlServer.Management.SMO.Scripter") ($srv)
      $scripter.Options = $scriptingOptions;
  
      $scripter.Script($allUrns)
  }
  
  Generate-SqlScript .\sqlexpress &lt;MyDbName&gt; &lt;FilePath&gt;
  </code></pre>
  
  <p>Now the problem is, WithDependencies option causes the view script to include its dependent tables, which was already included earlier. If I take out WithDependencies option, generated script does not reflect proper ordering.</p>
  
  <p>So <strong>the end result contains all the information, but it is not runnable. It raises an error since it cannot create the table twice.</strong></p>
  
  <p>I find too many posts talking about SMO scripter for this, so I assume there is gotta be something I missed. Or... did all those posts miss this problem?</p>