2010-05-12 20 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() 
} 
相關問題