[英]Create agent job from power shell script with including of power shell command
我嘗試使用 Power Shell 腳本自動執行 SQL Server 2016 安裝過程。 當我使用文件參數執行 Invoke-SqlCmd 時:
Invoke-SqlCmd -InputFile "..\res\test.sql" -ServerInstance "(local)" -Database "master" -ErrorAction Stop
其中包括帶有 power shell 命令的代理作業創建腳本:
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Erase Phantom System Health Records.',
@step_id=3,
@cmdexec_success_code=0,
@on_success_action=1,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N'PowerShell',
@command=N'if (''$(ESCAPE_SQUOTE(INST))'' -eq ''MSSQLSERVER'') {$a = ''\DEFAULT''} ELSE {$a = ''''};
(Get-Item SQLSERVER:\SQLPolicy\$(ESCAPE_NONE(SRVR))$a).EraseSystemHealthPhantomRecords()',
@database_name=N'master',
@flags=0
它因錯誤而停止:
Invoke-SqlCmd : 'INST' scripting variable not defined
顯然,這是我需要在創建之前轉義的 $ 字符。 有沒有人知道如何做到這一點? 我搜索過,但找不到任何有用的東西。
禁用 InvokeSQLcmd 的變量
Invoke-SqlCmd -InputFile "..\\res\\test.sql" -ServerInstance "(local)" -Database "master" -ErrorAction Stop -DisableVariables
PowerShell 正在嘗試解析您的$(ESCAPE_xxxx(yyyy))
塊,因此您需要在將其發送到 Invoke-SqlCmd 之前對其進行轉義。 最簡單的方法是使用replace
運算符:
$script = Get-Content "..\res\test.sql"
$script -replace '\(ESCAPE_(\w+)\((.+)\)\)','`(ESCAPE_$1`($2`)`)'
Invoke-SqlCmd -InputFile $script -ServerInstance "(local)" -Database "master" -ErrorAction Stop
顯然,您將無法對 SQL 命令塊中的每個括號進行轉義,但是您可以進行一些實驗來找出這種替換需要多窄或多寬。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.