1

I'm importing some values from a csv file and using them to create a adb command for an Android intent with the following code.

Write-Host adb shell am start -a android.intent.action.VIEW '-d' '"https://api.whatsapp.com/send?phone=' $($c.number)'"'

This gives me an out put of:

adb shell am start -a android.intent.action.VIEW -d "https://api.whatsapp.com/send?phone= 12345678 "

How can I remove the spaces where the variable is concatenated to the string to give the output of:

adb shell am start -a android.intent.action.VIEW -d "https://api.whatsapp.com/send?phone=12345678"
simonc
  • 87
  • 7
  • As an aside: [`Write-Host` is typically the wrong tool to use](http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/), unless the intent is to write _to the display only_, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file. To output a value, use it _by itself_; e.g, `$value`, instead of `Write-Host $value` (or use `Write-Output $value`); see [this answer](https://stackoverflow.com/a/60534138/45375). To explicitly print only to the display _but with rich formatting_, use `Out-Host`. – mklement0 Oct 25 '22 at 22:54
  • Specifically, using `Write-Host` here obscures the distinction between actual spaces in the arguments and multiple arguments being separated with spaces. – mklement0 Oct 25 '22 at 22:56

2 Answers2

2

Use string interpolation by switching to double quotes:

Write-Host adb shell am start -a android.intent.action.VIEW '-d' "`"https://api.whatsapp.com/send?phone=$($c.number)`""

Within double quotes, you have to backtick-escape double quotes to output them literally.

zett42
  • 25,437
  • 3
  • 35
  • 72
2

zett42's helpful answer is unquestionably the best solution to your problem.


As for what you tried:

Write-Host ... '"https://api.whatsapp.com/send?phone=' $($c.number)'"'
  • The fact that there is a space before $($c.number) implies that you're passing at least two arguments.

  • However, due to PowerShell's argument-mode parsing quirks, you're passing three, because the '"' string that directly follows $($c.number) too becomes its own argument.

Therefore, compound string arguments (composed of a mix of quoted and unquoted / differently quoted tokens) are best avoided in PowerShell.

Therefore:

Write-Host ... ('"https://api.whatsapp.com/send?phone=' + $c.number + '"')
mklement0
  • 382,024
  • 64
  • 607
  • 775