Home > Blockchain >  powerhsell script that makes multiple other powershell windows, and makes them all run one command s
powerhsell script that makes multiple other powershell windows, and makes them all run one command s

Time:07-12

I have:

for($i = 1 ; $i -le 3; $i  )
    {
        Start-Process powershell.exe
    }

but I don't know how I would make the new windows run a ping command. Could be done with an extra script but have no idea. Thanks

CodePudding user response:

Start-Process has an -ArgumentList parameter that can be used to pass arguments to the new PowerShell process.

powershell.exe and pwsh.exe have a -Command parameter that can be used to pass them a command.

You can combine the two like this:

for ($i = 1; $i -le 3; $i  ) 
{ 
    start-process powershell.exe -ArgumentList '-NoExit',"-Command ping 127.0.0.$i" 
}

If you don't use the -NoExit parameter the window will close as soon as the ping command finishes.

As mentioned in the comments to the question it is also possible to ping multiple hosts using the Test-Connection command like this:

Test-Connection -TargetName 127.0.0.1,127.0.0.2

This has a downside though in that it seems to ping one after the other rather than doing it in parallel.

Another way to do much the same thing in parallel, and probably more PowerShell style is to use jobs:

$jobs = @()
for ($i = 1; $i -le 3; $i  )
{
    $jobs  = Start-ThreadJob -ArgumentList $i { PARAM ($i)
        Test-Connection "127.0.0.$i"
    }
}
Wait-Job $jobs
Receive-Job $jobs -Wait -AutoRemoveJob

Note: Start-ThreadJob is newish. If you're still stuck on version 5 of PowerShell that comes with Windows use Start-Job instead, it spawns new processes where as Start-ThreadJob doesn't.

  • Related