Home > Net >  Start cmd from powershell with multiple arguments
Start cmd from powershell with multiple arguments

Time:09-02

Currently, I am able to call cmd from powershell using the following command:

Start-Process cmd -ArgumentList '/K "ping 192.168.1.1"'

What I am trying to do is add multiple arguments to pass onto the command, but it is not working. For example:

Start-Process cmd -ArgumentList '/K "title test" /K "ping 192.168.1.1"' 

Is there a way to do this?

Edit: My goal is to have a cmd window open, pinging the address listed, but also to pass the "title" argument so the window is titled.

Edit2: Here is my final solution based on the comments below:

$ips = @("/K title NAMEHERE & ping 192.168.1.15 -t")
$ips | ForEach-Object {
    Start-Process cmd -ArgumentList $_
}

CodePudding user response:

Since you're calling cmd.exe, use its statement-sequencing operator, &, to pass multiple commands to cmd /K:

Start-Process cmd -ArgumentList '/K title test & ping 192.168.1.1'

Note:

  • Start-Process's -ArgumentList (-Args) parameter technically accepts an array of arguments. While passing pass-through arguments individually may be conceptually preferable, a long-standing bug unfortunately makes it better to encode all arguments in a single string - see this answer.

  • cmd.exe's built-in title command inexplicably includes double quotes in the title if you enclose the argument in "..."; thus, if you want to specify a title that contains spaces, leave it unquoted and escape the spaces and any other metacharacters with ^; e.g., to pass test & more as the title, use title test^ ^& more

CodePudding user response:

start-process is sometimes tricky... try to add the elements as strings to an array and pass it over to start-process.

But in your case... idk what that /K should do, but in case of ping - ping is the process to start, not cmd ;-)

start-process ping.exe -argumentlist "127.0.0.1"

start-process ping.exe -argumentlist "127.0.0.1 /t"

as you are already using PowerShell

test-connection 127.0.0.1

Here is an example where I did something simliar:

$cmdArray = @(
                If ($token){
                    "-c"
                    "`"http.extraHeader=Authorization: Bearer $token`""
                }
                If ($clone){
                    'clone'
                }
                If ($fetch){
                    'fetch'
                    '-f'
                    'origin'
                    If ($tag){
                        "tags/$($tag):tags/$($tag)"
                    }
                }
                Else {
                    "`"$uri`""
                }
                If ($whatif){
                    '--dry-run'
                }
            )
            $result = Start-Process $pathGitexe -ArgumentList $cmdArray -Wait -NoNewWindow -PassThru

ok, based on your comment you need this:

$ips = @("192.168.1.1","192.168.1.2")

$ips | %{
    start-process ping.exe -ArgumentList $_
}
  • Related