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

3
  • 1
    possible duplicate. And you can't just concat several commands on a cmd command line like that. It's `command1 & command2 & command3`` Commented Jul 21, 2022 at 19:17
  • It would help if you were to explain your goal (so as to avoid the "XY problem"). Commented Jul 21, 2022 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% Commented Jul 22, 2022 at 13:46

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of call echo %name% you should perhaps use call echo %^name% for the case a variable name is already defined in advance…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.