To dynamically set the destination server name in your sqlcmd script, you can use the SERVERPROPERTY function to retrieve the machine name of the server where the SQL Agent job is running. However, since you want to ensure that the backup is written to the correct AG replica on the destination server, you will need to modify your script to refer to the destination server directly rather than relying on SERVERPROPERTY('MachineName') which retrieves the machine name of the source server.
Instead, you can pass the destination server name as a parameter to your script. Here’s how you can adjust your command:
sqlcmd -E -S Source_AG_listener -d master -Q "DECLARE @DestinationServer nvarchar(100) = 'Destination_Server_Name'; DECLARE @BackupPath NVARCHAR(1000) = '\\' + @DestinationServer + '\BackupFolder\DB_FULL.bak'; BACKUP DATABASE DB TO DISK= @BackupPath WITH INIT, COPY_ONLY;" -b
In this script, replace 'Destination_Server_Name' with the actual name of the destination server or use a variable that holds the name of the destination server where the job is running. This way, the backup will be correctly directed to the specified destination server's backup folder.
Make sure that the SQL Server service account has the necessary permissions to write to the specified backup folder on the destination server.