How to insert a variable into a long string with multiple quotation marks and escape characters?

Viewed 70

I have this really miserable line of code I need to work with that I haven't found a better way to do. My issue is I'm trying to get a variable inserted in the middle of this string, so normally I would just concatenate with +, but in this case the huge amount of quotation marks and escape characters have made this awful to try to do logistically. If anyone knows a simpler way of doing this I'd appreciate it- I'm sure there's an easy solution but I just can't get it. Here's the line:

Process.Start(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe ", @"""C:\Thunder\Scripts\script.ps1"" ""VARIABLE""");

So what I'm trying to do is put a string variable where the VARIABLE text is here. When I try to break it apart to concat, the combination of the @, the "s, and the \'s, I can't get the string apart in such a way that I can concat the variable into it. I assume there's an easier way here that I'm missing. Thanks.

1 Answers

You could use string interpolation:

$@"""C:\Thunder\Scripts\script.ps1"" ""{variable}""";

Using the $ prefix allows variables to be inserted using curly brackets, which will reduce the number of quotations in your case.


If variable is not a string, an implicit ToString() is called on the object instead.

Related