0

I am having difficulty with executing a command line in cmd from Powershell. The problem is I can't seem to use my global variables in the command line when cmd is opened from Poweshell. Below is the code I am working with but to no avail. Can someone please provide guidance on this issue?

Start-Process -FilePath "C:\Windows\System32\cmd.exe" -verb RunAs -ArgumentList {/k set Name="$cmdname" set Item="$cmditem" setlocal EnableDelayedExpansion echo "%Name%" }

Thanks, Roger

  • 1
    [possible duplicate](https://stackoverflow.com/a/30284028/2152082). And you can't just concat several commands on a `cmd` command line like that. It's `command1 & command2 & command3`` – Stephan Jul 21 '22 at 19:17
  • It would help if you were to explain your goal (so as to avoid the "XY problem"). – Bill_Stewart Jul 21 '22 at 19:29
  • `setlocal` won't have an effect when being executed in Command Prompt context (so in a command line in `cmd.exe /K` or `cmd /C`), it only works in a batch file. You could however use `cmd /V:ON …` to enable delayed expansion. Nevertheless, enabling alone is not enough, you also have to *use* it, like `!Name!` rather than `%Name%`… – aschipfl Jul 22 '22 at 13:46

1 Answers1

3

The syntax is awkward for sure:

Start-Process -FilePath "C:\Windows\System32\cmd.exe" -ArgumentList "/k set Name=$cmdname & set Item=$cmditem & call echo %name%"

Some of the reasoning here is:

  • cmd: additional commands need to be separated by &
  • cmd: the set command takes everything after = until special characters like &
  • cmd: setlocal EnableDelayedExpansion doesn't really apply here. Use call to delay instead.
    • delayed variable syntax is also !var! rather than %var%
  • Powershell: using brackets in -ArgumentList {stuff} sends as a literal string, and variables aren't expanded
Cpt.Whale
  • 4,784
  • 1
  • 10
  • 16
  • Instead of `call echo %name%` you should perhaps use `call echo %^name%` for the case a variable `name` is already defined in advance… – aschipfl Jul 22 '22 at 13:47