首页 > 解决方案 > Powershell + SMO 问题:如果 ScriptTransfer 没有先运行一次,则 ScriptTransfer 会跳过 EXECUTE AS?

问题描述

在尝试编写数据库脚本时,我遇到了一个奇怪的结果。该脚本有效,但我看到没有包含在 CLR SP 上的 EXECUTE AS CALLER 的位置,除非 ScriptTransfer() 首先运行一次,即使它被重定向到空值。

  1. 对带有 SP 的数据库运行以下脚本(我们正在使用带有 EXECUTE AS CALLER 的过程,该过程调用带有 EXTERNAL NAME 的 CLR)。
  2. 用 ScriptTransfer 和 OUT-NULL 注释掉该行并更改文件名
  3. 再次运行
  4. 比较文件。你会看到一个有 EXECUTE AS CALLER 而另一个没有。

这是我正在运行的脚本:

import-module sqlserver
$sql_server = "myservername"
$SMOServer = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList "$sql_server"
$DBToScript = "mydbname" 

$db = $SMOServer.Databases[$DBToScript]
$create_database = $db.Script() -replace("\d+KB","100mb") 

##### And now the rest of the database

$transfer = new-object -TypeName Microsoft.SqlServer.Management.Smo.Transfer #-ArgumentList $db
$transfer.Database = $db
$transfer.CopyAllObjects = $true
$transfer.CopySchema = $true
$transfer.ScriptTransfer() |out-null # for whatever reason this is necessary to script out the WITH EXECUTE AS CALLER in a CLR SP


cls
$transfer.CopyAllObjects = $true
$transfer.CopySchema = $true
$transfer.CopyAllSchemas= $true
$transfer.Options.Indexes = $true
$transfer.Options.ScriptBatchTerminator = $true # this only goes to the file
$transfer.Options.filename = "c:\temp\backup\resultsa.sql"
$transfer.Options.ExtendedProperties= $true # yes, we want these
$transfer.Options.DRIAll= $true # and all the constraints 
$transfer.Options.Indexes= $true # Yup, these would be nice
$transfer.Options.Triggers= $true # This should be included when scripting a database
$transfer.Options.ScriptBatchTerminator = $true # this only goes to the file
$transfer.Options.IncludeHeaders = $false #pshaw
$transfer.Options.ToFileOnly = $true #no need of string output as well
$transfer.Options.IncludeIfNotExists = $false # not necessary but it means the script can be more versatile

$transfer.ScriptTransfer()  

标签: sql-serverpowershellsmo

解决方案


推荐阅读