Frage

I am trying to write a Powershell script to generate a SQL script that creates the stored procedures in my database. Here is what I have:

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')| out-null

Function to-array ($c)
{
    foreach($item in $c)
    {
      $result += @($item)
    }
    $result
}

$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') "LOCALHOST"
$scrp = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($s)
$dbs = $s.Databases
$fa = $dbs["FinancialAid"]

$scrp.Options.ScriptData = $True
$scrp.Options.AllowSystemObjects = $False
$scrp.Options.FileName = 'StoredProcedures.sql'
$scrp.Options.ToFileOnly = $True

# Finally the stored procedures

$sparray = to-array($fa.StoredProcedures)
$scrp.EnumScript($sparray)

This fails with the error:

Exception calling "EnumScript" with "1" argument(s): "Script failed for Server 'LOCALHOST'. "
At H:\Visual Studio 2012\FinancialAidApplication\Financial Aid Application\FinancialAidApplication\main\src\FinancialAidApp
\SQL-Scripts\sp.ps1:28 char:17
+ $scrp.EnumScript <<<< ($sparray)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Looking at the output file, I see that it does have my stored procedures at the beginning, which is great, but then it has a bunch of system procedures. The last one is sys.sp_fulltext_table.

As I already specified $scrp.Options.AllowSystemObjects = $False I don't understand why these system procedures are being included. I would like to get rid of the system procedures and the error message.

War es hilfreich?

Lösung

Or you could just skip the array completely and just use the pipeline. (From a piece of something I use regularly but modified you use your variables)

add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
$s= new-object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList 'LOCALHOST'
$fa = $s.Databases['FinancialAid']
   $scrp = New-Object ("Microsoft.SqlServer.Management.Smo.Scripter")
   $scrp.Server = $s
   $options = New-Object ("Microsoft.SqlServer.Management.SMO.ScriptingOptions")
   $options.IncludeHeaders = $true
   $options.FileName = 'C:\temp\StoredProcedures.sql'
   $options.AppendToFile = $true
   $options.ToFileOnly = $true
   $options.ScriptBatchTerminator = $true
   $scrp.Options = $options
$fa.StoredProcedures | foreach {if ($_.IsSystemObject -eq $false) { $scrp.Script($_) }}

Andere Tipps

A couple of things

  1. Try to get to the actual exception. Throw "inner exception powershell" into your favorite search engine. Right now, it's just a generic "something went wrong", which is hard to diagnose (both for you and for us!).

  2. Try $sparray = to-array($fa.StoredProcedures | where {$_.IsSystemObject -eq $false)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top