Enable xp_cmdshell in SQL Server (and Turn It Off Again)

Turns on xp_cmdshell with sp_configure (SQL Server 2016 to 2022; Windows only, it is not available on SQL Server on Linux). Only turn it on if a job needs it, and turn it off again afterwards. A sysadmin can run it straight away; anyone else needs a proxy account set up with sp_xp_cmdshell_proxy_account.

-- Check the current setting
SELECT name, value_in_use
FROM sys.configurations
WHERE name = N'xp_cmdshell';

-- Allow advanced options to be changed
EXEC sys.sp_configure N'show advanced options', 1;
RECONFIGURE;

-- Enable xp_cmdshell
EXEC sys.sp_configure N'xp_cmdshell', 1;
RECONFIGURE;

-- Hide the advanced options again
EXEC sys.sp_configure N'show advanced options', 0;
RECONFIGURE;

-- To turn it off again when the job is done
-- EXEC sys.sp_configure N'show advanced options', 1; RECONFIGURE;
-- EXEC sys.sp_configure N'xp_cmdshell', 0; RECONFIGURE;
-- EXEC sys.sp_configure N'show advanced options', 0; RECONFIGURE;