Home > database >  Run new instance of CMD in PowerShell without a long string of text
Run new instance of CMD in PowerShell without a long string of text

Time:05-07

So i was wondering if there was a way to remove all of the "&" when you're running an instance of cmd with arguments through PowerShell

For example:

start-process cmd -ArgumentList "/C","timeout /t 5 /nobreak & echo hello & timeout /t 5 /nobreak"

Turn into something like:

start-process cmd -ArgumentList "/C", {
  "timeout /t 5 /nobreak" 
  "echo hello"
  "timeout /t 5 /nobreak"
}

Im new so idk

CodePudding user response:

-ArgumentList takes a array of strings, and the array subexpression operator (@(...)) can span multiple lines:

Start-Process cmd -ArgumentList @(
  "/C"
  "timeout /t 5 /nobreak &"
  "echo hello &"
  "timeout /t 5 /nobreak"
)

CodePudding user response:

The problem is that cmd.exe's /c and /k parameters do not support multi-line strings as arguments, so in order to submit multiple commands, you must use & to concatenate them on a single line.

However, you can let PowerShell do the work for you, which allows you to use a multi-line string on the PowerShell side, as you would write commands in a batch file:

Start-Process cmd '/c', (@'
  timeout /t 5 /nobreak
  echo hello
  timeout /t 5 /nobreak
'@ -split '\r?\n' -join ' & ')

The above uses:

  • A verbatim here-string (@'<newline>...<newline>'@) for the multi-line string.

    • Important: The closing here-string delimiter, '@ in this case, must be _at the very start of a line - not even whitespace may precede it.

    • If you need string interpolation, use the expandable here-string variant, @"<newline>...<newline>"@

  • -split '\r?\n' splits the multi-line string into individual lines...

  • ... which -join ' & ' then joins together to form a single-line string in which the lines are concatenated with  & , as in your question.

  • Related