So I am trying to write a script that allows me to open several cmd command prompt and write in them the same command but with different variables.
The solution that I came with was to write a PowerShell script that calls inside a loop a cmd file and pass a variable each time to the cmd file but I'm stuck, the PowerShell script execute only one cmd.
Can someone help to figure this out ?
Thanks :)
CodePudding user response:
You can use the following :
cmd.exe /c [command]
for example
$x = 1..100
foreach ($n in $x){cmd.exe /c ping 192.168.1.$n}
CodePudding user response:
mohamed saeed's answer shows you to execute cmd.exe
commands synchronously, in sequence in the current console window.
If, by contrast, you want to open multiple interactive cmd.exe
sessions, asynchronously, each in its separate, new window, use cmd.exe
's /k
option and invoke cmd.exe
via Start-Process
:
# Open three new interactive cmd.exe sessions in new windows
# and execute a sample command in each.
'date /t', 'ver', "echo $PSHOME" | ForEach-Object {
# Parameters -FilePath and -ArgumentList implied.
Start-Process cmd.exe /k, $_
}
Note:
Unless your
cmd.exe
console windows have theLet the system position the window
checkbox in the Properties dialog checked by default, all new windows will fully overlap, so that you'll immediately only see the last one opened.The last new window opened will have the keyboard focus.
The commands passed to
/k
are instantly executed, but an interactive session is then entered.
CodePudding user response:
If you would like to keep in purely batch, you can use the start command. The /k switch keeps the command line open. You would use /c if you want to carry out the command and terminate :
start "" %comspec% /k ping 192.168.1.1
From powershell, you can use the Start-Process command with an ArgumentList:
Start-Process cmd.exe -ArgumentList "/k ping 192.168.1.1"