Powershell显示数组的所有内容,而不是一次执行一个步骤

时间:2018-09-20 18:09:30

标签: arrays powershell for-loop concatenation

我是Powershell的新手,我正在研究一个脚本,该脚本打开edge并搜索bing以查找特定术语。我有一个术语数组,以及一个遍历该数组的for循环。该循环有效,但不是在每个循环上显示一个数组项,而是使用所有项。这是我的脚本:

#create dictionary
$diction = @("iphone","android","untidy","stew","camp","fresh","groan","warlike","party","bake","zephyr","play","lamp")

#loop
For ($i=0; $i -lt $diction.Length; $i++) {

    start microsoft-edge:http://www.bing.com/search?q=$diction[$i]
    Start-Sleep -s 5
    TASKKILL /IM MicrosoftEdge.exe

}

Read-Host -Prompt "Press Enter to exit"

代替 http://www.bing.com/search?q=iphone 然后http://www.bing.com/search?q=android,依此类推,实际结果是 http://wwwbing.com/search?q= iphone android不整洁的炖菜营新鲜camp吟战争般的聚会烤西风播放灯

我是否缺少有关如何在Powershell中显示数组项的信息? 感谢您的任何帮助。

2 个答案:

答案 0 :(得分:2)

像这样更新您的代码。此外,通过为命令使用变量,您可以使用ISE或VSCode之类的调试器来实际查看正在传递的内容。

$cmd = "microsoft-edge:http://www.bing.com/search?q=$($diction[$i])"
start $cmd

答案 1 :(得分:0)

如果您正在执行Powershell,则应使用管道 | 代替for语句 在管道期间,传递的值存储为 $ _ Foreach对象的目标为 基本上是将数组通过管道传递给foreach对象

"iphone","android","untidy","stew","camp","fresh","groan","warlike","party","bake","zephyr","play","lamp" | 
    %{
        start microsoft-edge:http://www.bing.com/search?q=$_
        Start-Sleep -s 5
        TASKKILL /IM MicrosoftEdge.exe
    }
Read-Host -Prompt "Press Enter to exit"