2

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.

Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73
GBarron
  • 33
  • 6
  • 1
    https://stackoverflow.com/questions/31638579/how-to-use-verbatim-strings-with-interpolation – Dzianis Karpuk May 07 '21 at 14:38
  • Thank you @DzianisKarpuk for the link. I tried to search for this first, but not knowing what exact search terms to use, I didn't find that question. – GBarron May 07 '21 at 15:49

1 Answers1

4

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.

Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
  • It looks like this worked! I'll need to run some tests to make sure it's behaving as expected, but so far it's looking good! Thanks for the assist, this saves me a lot of headaches. Programming is kind of a tertiary role at the job so I have a lot to learn still. – GBarron May 07 '21 at 15:36
  • And testing confirmed, works perfectly. Thanks again. – GBarron May 07 '21 at 15:44