如何在PowerShell中无空格拼接变量与字符串(adb命令场景)
问题:去除PowerShell字符串拼接空格,生成正确的adb Intent命令
我从CSV文件导入数据,用以下PowerShell代码生成调用Android Intent的adb命令:
Write-Host adb shell am start -a android.intent.action.VIEW '-d' '"https://api.whatsapp.com/send?phone=' $($c.number)'"'
当前生成的命令输出如下:
adb shell am start -a android.intent.action.VIEW -d "https://api.whatsapp.com/send?phone= 12345678 "
我需要去掉变量与字符串拼接处的空格,得到目标输出:
adb shell am start -a android.intent.action.VIEW -d "https://api.whatsapp.com/send?phone=12345678"
解决方法
方法1:使用PowerShell字符串插值(推荐)
利用PowerShell的双引号字符串插值特性,直接将变量嵌入字符串中,同时用Trim()清除变量前后的空格,避免拼接时产生多余空格:
Write-Host "adb shell am start -a android.intent.action.VIEW -d `"https://api.whatsapp.com/send?phone=$($c.number.Trim())`""
方法2:用字符串连接符+拼接
将需要拼接的部分用括号包裹,通过+直接连接字符串和处理后的变量,避免PowerShell在参数间自动添加空格:
Write-Host adb shell am start -a android.intent.action.VIEW '-d' ('"https://api.whatsapp.com/send?phone=' + $c.number.Trim() + '"')
关键说明
- 原输出中的空格一方面来自
Write-Host对多个参数自动添加的分隔空格,另一方面是$c.number本身可能包含的前后空格,所以调用Trim()是必要的。 - 用双引号包裹整个命令字符串时,内部的双引号需要用反引号
`转义,避免语法错误。
内容的提问来源于stack exchange,提问作者simonc
相关产品推荐
相关产品推荐

