I have simplified my issues so that it can be reprod by anyone .
I have a sql agent job with powerhsell step with below code -
$sqlInstance = "$(ESCAPE_DQUOTE(SRVR))"
$sql_conn = New-Object system.Data.SqlClient.SqlConnection
$sql_conn.ConnectionString = "Data Source=$sqlInstance;Integrated Security=true;Initial Catalog=master;"
$sql_conn.Open()
$cmd = new-Object System.Data.SqlClient.SqlCommand
$cmd.connection = $sql_conn
$cmd.CommandText= " select 1 "
$cmd.executenonquery()
$sql_conn.Close()
I scripted out the above job and wanted to deploy using SQLCmd
sqlcmd -SMyServer -i "C:\Temp\testjob.sql"
I get below error in SQLCMD executin window - 'SRVR' scripting variable not defined. But job gets created though with below code -
(note the missing ESCAPE_DQUOTE in $sqlInstance = "$((SRVR))" )
$sqlInstance = "$(SRVR)"
$sql_conn = New-Object system.Data.SqlClient.SqlConnection
$sql_conn.ConnectionString = "Data Source=$sqlInstance;Integrated Security=true;Initial Catalog=master;"
$sql_conn.Open()
$cmd = new-Object System.Data.SqlClient.SqlCommand
$cmd.connection = $sql_conn
$cmd.CommandText= " select 1 "
$cmd.executenonquery()
$sql_conn.Close()
The created job fails complaining on missing ESCAPE_xxx macro.
As suggested in one of the posts If I remove the script file - $ before (ESCAPE_DQUOTE(SRVR))
Job gets created with
$sqlInstance = "(ESCAPE_DQUOTE(SRVR))"
@ReturnCode = msdb.dbo.sp_add_jobstep@job_id=@jobId, @step_name=N'step 1',
@step_id
=1,
@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'$sqlInstance = "$(ESCAPE_DQUOTE(SRVR))"
$sql_conn = New-Object system.Data.SqlClient.SqlConnection
$sql_conn.ConnectionString = "Data Source=$sqlInstance;Integrated Security=true;Initial Catalog=master;"
$sql_conn.Open()
$cmd = new-Object System.Data.SqlClient.SqlCommand
$cmd.connection = $sql_conn
$cmd.CommandText= " select 1 "
$cmd.executenonquery()
$sql_conn.Close()
'
,
@database_name
=N'master',
@flags
=0