PowerShell 直接对比 SQL 代理 PowerShell 作业步骤

PowerShell directly vs. SQL Agent PowerShell Job Steps

如果我 运行 Powershell 中的这 3 行脚本(运行 作为管理员,并且我的域帐户是 MyRemoteServer 上的本地管理员),它会按预期工作(注意有美元登录我必须用反引号转义的服务名称):

Invoke-Command -ComputerName "MyRemoteServer" -ScriptBlock{Get-Service -Name "AOS60`" | Stop-Service -Force}
get-service -Name "AOS60`" -ComputerName "MyRemoteServer" | Format-Table -Property MachineName, Status, Name, DisplayName -auto
Invoke-Command -ComputerName "MyRemoteServer" -ScriptBlock{Get-Service -Name "AOS60`" | Start-Service}

[第 2 步是提供证据证明服务在第 1 步之后实际上具有 "Stopped" 的状态。一旦成功转换为代理作业,第 2 步将实际调用一个存储过程,执行一系列操作数据库恢复。]

如果我将这些语句作为作业步骤放入 SQL Agent (SQL Server 2012 SP2) 并启动作业,作业会崩溃(它不仅仅是失败,它想调用调试器)在第一步。 运行 作为 SQL 代理服务的域服务帐户据称被我们的运营组授予了对 MyRemoteServer 的必要权限。

作业脚本遇到以下错误。这些错误没有停止脚本:

Unhandled Exception: System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list. at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args) at System.String.Format(IFormatProvider provider, String format, Object[] args) at Microsoft.SqlServer.Management.PowerShell.Res.GetString(String key, Object arg0) at Microsoft.SqlServer.Management.PowerShell.SqlPowerShell.GetErrorRecordMessage(ErrorRecord errorRecord) at Microsoft.SqlServer.Management.PowerShell.SqlPowerShell.HandleAgentJob(RunspaceConfiguration config) at Microsoft.SqlServer.Management.PowerShell.SqlPowerShell.Main(String[] args)

我在下面编写了作业以供参考。请注意,即使我省略了 @output_file_name,它也会失败,因此问题不在于写入输出文件,而在于执行步骤本身。

USE [msdb]
GO

/****** Object:  Job [Test stopping and restarting AX]    Script Date: 6/21/2017 1:49:30 PM ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object:  JobCategory [[Uncategorized (Local)]]    Script Date: 6/21/2017 1:49:30 PM ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END

DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'Test stopping and restarting AX', 
        @enabled=1, 
        @notify_level_eventlog=0, 
        @notify_level_email=0, 
        @notify_level_netsend=0, 
        @notify_level_page=0, 
        @delete_level=0, 
        @description=N'No description available.', 
        @category_name=N'[Uncategorized (Local)]', 
        @owner_login_name=N'ROGUE\amfreeman', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Synchronously Stop AX Service on DEVAOS2]    Script Date: 6/21/2017 1:49:30 PM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Synchronously Stop AX Service on DEVAOS2', 
        @step_id=1, 
        @cmdexec_success_code=0, 
        @on_success_action=3, 
        @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'Invoke-Command -ComputerName "MyRemoteServer" -ScriptBlock{Get-Service -Name "AOS60`" | Stop-Service -Force}', 
        @database_name=N'master', 
        @output_file_name=N'E:\Microsoft SQL Server\MSSQL11.RELEASE\MSSQL\Log\Test_stopping_and_restarting_AX_$(ESCAPE_SQUOTE(STEPID))_Synchronously_Stop_AX_Service_on_DEVAOS2.txt', 
        @flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Get status of  AX Service on DEVAOS2]    Script Date: 6/21/2017 1:49:30 PM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Get status of  AX Service on DEVAOS2', 
        @step_id=2, 
        @cmdexec_success_code=0, 
        @on_success_action=3, 
        @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'get-service -Name "AOS60`" -ComputerName "MyRemoteServer" | Format-Table -Property MachineName, Status, Name, DisplayName -auto', 
        @database_name=N'master', 
        @output_file_name=N'E:\Microsoft SQL Server\MSSQL11.RELEASE\MSSQL\Log\Test_stopping_and_restarting_AX_$(ESCAPE_SQUOTE(STEPID))_Get_status_of__AX_Service_on_DEVAOS2.txt', 
        @flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Synchronously Start AX Service on MyRemoteServer]    Script Date: 6/21/2017 1:49:30 PM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Synchronously Start AX Service on MyRemoteServer', 
        @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'Invoke-Command -ComputerName "MyRemoteServer" -ScriptBlock{Get-Service -Name "AOS60`" | Start-Service}', 
        @database_name=N'master', 
        @output_file_name=N'E:\Microsoft SQL Server\MSSQL11.RELEASE\MSSQL\Log\Test_stopping_and_restarting_AX_$(ESCAPE_SQUOTE(STEPID))_Synchronously_Start_AX_Service_on_MyRemoteServer.txt', 
        @flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:

如何才能将 SQL 代理作业正确地 运行?

我强烈建议不要在 SQL 代理中使用 PoSH 作业步骤。这是因为执行的 PoSH 版本可能不是您期望执行的版本。

为了调用 PoSH 脚本,我只使用调用 PoSH 可执行文件的 CmdExec 作业步骤。我的脚本也使用 PoSH 远程处理,我没有遇到任何问题。

有两个问题:

1) 注意我原来的post这句话中的"allegedly"这个词:"The domain service account that runs the SQL Agent Service was allegedly granted the necessary permissions on MyRemoteServer by our Operations group."事实证明,所有需要的权限都没有被授予域帐户运行 SQL 服务器代理服务。

2) 我采纳了@NedOtter(以及其他各种博客和 Stack posts)的建议,并通过 CmdExec 转换为使用 PowerShell。我不知道这是必要的,但这似乎是对前进道路的共识。

我使用了两个作业步骤,@command 参数中包含以下内容:

C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe "Invoke-Command -ComputerName ''MyRemoteServer'' -ScriptBlock{Get-Service -Name ''AOS60'' | Stop-Service -Force}"
C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe "Invoke-Command -ComputerName ''MyRemoteServer'' -ScriptBlock{Get-Service -Name ''AOS60'' | Start-Service}"

这些结合起来同步停止然后启动服务。然后我在中间插入了一个作业步骤,从我的生产备份中恢复这个测试实例中的数据库。