Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Escape double quotes in command parameter

I need to run a PS command on SQL Server. Running a simple command without double-quotes works without a problem.

How to run below command?

DECLARE @sql nvarchar(4000);
 SET @sql = 
 '
 powershell.exe -command "
 $messageBody = "ds"
 Write-Host $messageBody
 "';
EXEC xp_cmdshell @sql;

I tried this ` and backslash but nothing seems to be working.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Running it from ps1 file is not an option.

>Solution :

Instead of "ds", use ''ds'' to use single quotes withing the ps script to enclose the literal. Furthermore, use the call operator (&) withing the command parameter to call the script block:

SET @sql = 'powershell.exe -command "& { $messageBody = ''ds''; Write-Host $messageBody }';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading