完整问题:使用 Invoke SQL 命令使用 Powershell 脚本,使用 snappins,我需要将它们包含在 SQL 作业中,Powershell 的 SQL Server 版本有些残缺,有人知道解决方法吗?
根据我收集到的信息,SQL Management Studio 的 powershell 版本功能不足,不允许使用 snappin,因此它无法识别我在脚本中使用的 cmdlet。我尝试在作业中将其作为命令行提示符而不是 Powershell 脚本运行,这会导致代码在一定程度上起作用,但是我检查了作业的历史记录,它说 invoke-sql 仍然不是可识别的 cmdlet。我推测,因为我在远程服务器上运行代码,使用的凭据与我的标准不同,我的预加载 snappin 的配置文件没有被加载,尽管这有点令人怀疑。
此外,由于我是一个 powershell 菜鸟,任何关于更好的编码实践/简化我的代码的建议都将不胜感激!
代码如下:
# define parameters
param
(
$file = "\\server\folder\file.ps1"
)
"invoke-sqlcmd -query """ | out-file "\\server\folder\file.ps1"
# retrieve set of table objects
$path = invoke-sqlcmd -query "select TableName from table WITH (NoLock)" -database db -server server
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$so = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions
$so.DriPrimaryKey = $false
$so.Nocollation = $true
$so.IncludeIfNotExists = $true
$so.NoIdentities = $true
$so.AnsiPadding = $false
# script each table
foreach ($table in $path)
{
#$holder = $table
$table = get-item sqlserver:\sql\server\default\databases\database\tables\dbo.$($table.TableName)
$table.script($so) | out-file -append $file
}
(get-content "\\server\folder\file.ps1") -notmatch "ANSI_NULLS" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -notmatch " AS "| out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -notmatch "Quoted_" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace "\) ON \[PRIMARY\].*", ")" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace "\[text\]", "[nvarchar](max)" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace " SPARSE ", "" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace "COLUMN_SET FOR ALL_SPARSE_COLUMNS", "" | out-file "\\server\folder\file.ps1"
""" -database database -server server" | out-file "\\server\folder\file.ps1" -append