Search code examples
powershellvariablesquotessql-server-expresssingle-quotes

Powershell variable that contains double and single quotes


Admittedly noob question... I'm trying to set up a PowerShell script to create scheduled tasks to backup a SQL Express database. I'm following the instructions here:

https://blogs.technet.microsoft.com/heyscriptingguy/2015/01/16/use-powershell-to-create-scheduled-task-in-new-folder/

They work beautifully for most tasks, but the argument I need to make already contains double and single quotes, and it's throwing everything off. The argument I have in Task Scheduler is:

/C osql -U sa -P Password -S localhost\INSTANCE -Q "Backup Database DATABASE to disk = 'C:\DB Backups\database.bak' with init"

With both quotes and single quotes in this, how do I turn this entire string into a variable?

EDIT: The specific part that's failing is:

Function Create-AndRegisterApplogTask

{

 Param ($taskname, $taskpath)

 $action = New-ScheduledTaskAction -Execute 'CMD' -Argument "/C osql -U sa -
P Password -S localhost\INSTANCE -Q "Backup Database DATABASE to disk = 'C:\DB Backups\database.bak' with init""

 $trigger =  New-ScheduledTaskTrigger -Daily -At 9am

 Register-ScheduledTask -Action $action -Trigger $trigger -TaskName 
$taskname -Description "Daily Backup of IRWSDB Database" -TaskPath $taskpath

}

It's erring because it's seeing

"/C osql -U sa -P Cedara123 -S localhost\WEBACCESS -Q "

in quotes, then seeing:

Backup Database IRWSDB to disk = 

outside of quote, and then

'C:\DB Backups\IRWSDB.bak'

in single quotes, followed again by

with init

outside of quotes finally followed by just:

""

I've also tried changing the -Argument parameter to just $Argument and trying to declare:

$argument = "/C osql -U sa -P Password -S localhost\INSTANCE -Q "Backup Database DATABASE to disk = 'C:\DB Backups\database.bak' with init""

But I still can't figure out how to get it to show as a single line of text.


Solution

  • You can escape the double-quotes inside the string using a backtick. Try:

    $Arguments = "/C osql -U sa -P Password -S localhost\INSTANCE -Q `"Backup Database DATABASE to disk = 'C:\DB Backups\database.bak' with init`"" 
    

    Usually I end up with a batch-script for the action if the command gets too tricky.