Can't manipulate the string in powershell while calling the script in C# Windows Application

102 Views Asked by At

I am trying to take backup of SQL Server database using PowerShell and then making windows application around it. But it is not working. I think I have mingled up the strings by putting wrong double quotes and single quotes. Following is the code in C# where I am calling the PowerShell script.

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Import-Module SQLPS -DisableNameChecking");
pipeline.Commands.AddScript("$dt=Get-Date -Format '" + dtFormat + "' ");
pipeline.Commands.AddScript("$dbname = '" + dbName + "'");
pipeline.Commands.AddScript("$backup = " +bckFolderPath +@"\$($dbname)_db_$($dt).bak");
pipeline.Commands.AddScript("Backup-SqlDatabase -ServerInstance '" + serverName + "' -Database $dbname -BackupFile" + " $backup");

runspace.Close();

What can I do as this is not taking backup but if I run the script in PowerShell, then it is working.

1

There are 1 best solutions below

0
veljkoz On

You do realize that the commands you provided in your comment (that you say are working in PS) aren't the same as the ones you push through c#? The $backup line doesn't exist in your PS commands...

Anyway, I believe the error could be in the $backup line, missing quotes around the path...

pipeline.Commands.AddScript("$backup = '" +bckFolderPath +@"\$($dbname)_db_$($dt).bak'");