2010-05-12 35 views
1

我试图从数据库中生成脚本,但对这些对象进行了轻微的修改。例如,我想为存储过程生成脚本,但我希望脚本在不同的模式下创建它。如何在PowerShell中使用SMO来脚本轻微更改对象?

我有什么,我目前正在下面的例子。如果我正在朝一个完全错误的方向前进,那么请指点我正确的方向。我想避免做任何类型的字符串搜索和替换,因为这有很多潜在的危险。

我试图做的是在数据库中创建从已有的功能函数对象,然后我提出一个新的,尽量做到,我刚刚创建的一个副本。这似乎有必要让我改变模式,因为它必须在内存中,而不是绑定到数据库。然后我尝试更改模式并将其编写出来。不幸的是,我一直无法找到.Script的语法,它不会因Pow​​erShell中的错误而失败。

$instance = $args[0] # Gets the instance name from the command line parameters 
$database = $args[1] # Gets the database name from the command line parameters 

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

# Create an instance for the SQL Server 
$serverInstance = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $instance 

# Create an instance for the Database 
$databaseInstance = $serverInstance.Databases[$database] 

# Loop through all of the user defined functions (that are not system objects) in the database 
foreach ($function in $databaseInstance.UserDefinedFunctions | Where-Object {$_.IsSystemObject -eq $False}) 
{ 
    $newFunction = New-Object ('Microsoft.SqlServer.Management.Smo.UserDefinedFunction') ($databaseInstance, $function.Name, "tnf_dbo_func") 

    $newFunction.TextHeader = $function.TextHeader 
    $newFunction.TextBody = $function.TextBody 

    $newFunction.TextMode = $False 
    $newFunction.ChangeSchema("tnf_dbo_func") 
    $newFunction.TextMode = $True 

    Write-Host $newFunction.Schema 
    Write-Host $newFunction.TextHeader 
    Write-Host $newFunction.TextBody 
    $newFunction.Script() 
} 

回答

3

当我在我的问题中输入时,我意识到.TextMode设置来自我尝试的另一个解决方案。删除那些修复问题。由于问题已经输入,我想我会发布它,以防止这可以帮助别人。

校正的代码:

$instance = $args[0] # Gets the instance name from the command line parameters 
$database = $args[1] # Gets the database name from the command line parameters 

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

# Create an instance for the SQL Server 
$serverInstance = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $instance 

# Create an instance for the Database 
$databaseInstance = $serverInstance.Databases[$database] 

# Loop through all of the user defined functions (that are not system objects) in the database 
foreach ($function in $databaseInstance.UserDefinedFunctions | Where-Object {$_.IsSystemObject -eq $False}) 
{ 
    $newFunction = New-Object ('Microsoft.SqlServer.Management.Smo.UserDefinedFunction') ($databaseInstance, $function.Name, "tnf_dbo_func") 

    $newFunction.TextHeader = $function.TextHeader 
    $newFunction.TextBody = $function.TextBody 

    $newFunction.ChangeSchema("tnf_dbo_func") 

    Write-Host $newFunction.Schema 
    Write-Host $newFunction.TextHeader 
    Write-Host $newFunction.TextBody 
    $newFunction.Script() 
}