simonc
simonc

Reputation: 87

How can I concatenate a variable and string without spaces in powershell

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"

Upvotes: 1

Views: 424

Answers (2)

mklement0
mklement0

Reputation: 437062

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 + '"')

Upvotes: 2

zett42
zett42

Reputation: 27756

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.

Upvotes: 2

Related Questions