Search code examples
sql-serverpowershellstored-proceduresbackup

Powershell SQL Server stored procedure backup


I am trying to backup one particular stored procedure from a SQL Server database by passing parameters from a Python program. Here is the code that I have tried but I keep getting an error.

param([string]$server='dbsed0898', [string]$dbname='global_hub',[string]$sp='dbo.gs_eligibility')

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

$SMOserver = 'Microsoft.SqlServer.Management.Smo' #-argumentlist $server
$srv = New-Object("$SMOserver.Server") $server
$db = $srv.databases[$dbname]

$Objects = $db.storedprocedures[$sp]
$scripter = new-object ("$SMOserver.Scripter") $srv

$Scripter.Script($Objects) | Out-File 
" C:\Users\fthoma15\Documents\backup_03212020.sql"

$db = $SMOserver.databases[$dbname]

$Objects = $db.storedprocedures[$sp]
$Scripter.Script($Objects) | Out-File 

"C:\Users\fthoma15\Documents\backup_03212020.sql"

Error:

Multiple ambiguous overloads found for "Script" and the argument count: "1".
At line:12 char:5
+ $Scripter.Script($Objects) | Out-File "C:\Users\fthoma15\Document ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest

Can someone help me?


Solution

  • Here is what i did.

    param([string]$server='test', [string]$dbname='test',[string[]]$sp=('test','test'))
    
    [System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.SMO”) | out- 
    null
    
    $SMOserver = new-object ("Microsoft.SqlServer.Management.Smo.Scripter") #-argumentlist 
    $server
    $srv = new-Object Microsoft.SqlServer.Management.Smo.Server("$server")
    $db = New-Object Microsoft.SqlServer.Management.Smo.Database
    $db = $srv.Databases.Item("$dbname")
    $Objects = $db.storedprocedures[$sp[1,3]]
    $scripter = new-object ("$SMOserver") $srv
    
    $Scripter.Script($Objects) | Out-File 
    "C:\Users\fthoma15\Documents\backup_03212020.sql"
    

    As suggested by AlwaysLearning, i changed the sp variable to an array list,splitting both schema and sp name.