Search code examples
powershellcmd

Use PowerShell variables in cmd command not working


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


Solution

  • 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