-1

I need to run a for loop, from powershell, in cmd... aka, at the PS Prompt:

cmd /c For /L %i in (1,1,5) DO (Echo %i)

But, I get a "1 is unexpected at this time"

Other responses in my research indicate "%i" is command line, and "%%i" is script/batch -- but I've tried both and neither worked. Any ideas? Is it not possible?

JosefZ
  • 1,564
  • 1
  • 10
  • 18
Jeff
  • 1
  • 1
  • 1
  • 2
    `cmd /c 'For /L %i in (1,1,5) DO (Echo %i)'` – user240633 Mar 03 '19 at 06:05
  • Awesome, thank you! I encountered another problem later and was working with single quotes to resolve it -- don't know why i didn't think of it here. Thanks so much!! – Jeff Mar 03 '19 at 19:59
  • 1
    Why would you want to do a `cmd` script from PowerShell? Instead do it in PowerShell: `1..5 |% { Write-Host $_ }` – Matthew Wetmore Mar 03 '19 at 20:49

1 Answers1

0

By the About Quoting Rules help topic (Get-Help about_quoting_rules -Full), use single or double quotes as follows:

. cmd /c 'For /L %i in (2,2,5) DO @(Echo %i)'
2
4

or

$step=2
. cmd /c "For /L %i in (2,$step,5) DO @(Echo %i)"
2
4

However, by the About Parsing help topic (Get-Help about_parsing -Full), there are more ways to achieve this:

  • by ad hoc escaping some PowerShell-poisonous symbols e.g. () parentheses, $ Dollar Sign, @ Commercial At etc., see also Get-Help about_Escape_Characters (online version not found). In Windows PowerShell, the escape character is the ` backtick, also called the grave accent (codepoint U+0060, ASCII 96).:
cmd /c For /L %i in `(2,1,4`) DO `@`(Echo %i`)
2
3
4
  • by using the stop-parsing symbol (--%)` (introduced in PowerShell 3.0, directs PowerShell to refrain from interpreting input as PowerShell commands or expressions). This technique is much easier than using escape characters to prevent misinterpretation:
cmd /c --% For /L %i in (2,1,4) DO @(Echo %i)
2
3
4
JosefZ
  • 1,564
  • 1
  • 10
  • 18