Search code examples
powershellcmd

Run cmd from a given folder inside PowerShell script


Is there any possibility to run a cmd command from a different folder then the script home location (e.g. C:\ScriptHome)?

I mean e.g.

Cmd /C "C:\Test\test.exe"
  • but this exe should be called from e.g. "C:\RunTestExeHere"

Basically, it can be done in pure cmd, like cd "C:\RunTestExeHere" and after

C:\RunTestExeHere>C:\Test\test.exe
  • but can it be done in powershell?

Thank you!


Solution

  • Your best bet is to sandwich your external command between Push-Location and Pop-Location commands.

    A simple example (-EA is short for the common -ErrorAction parameter):

    Push-Location -EA Stop C:\  # You'd use C:\RunTestExeHere instead; 
    cmd /c dir                  # You'd use & "C:\Test\test.exe" instead
    Pop-Location                # Return to the original dir.
    

    Note:

    Thus, to ensure that Pop-Location is always executed, call it from the finally block of a try statement:

    # Safer version
    Push-Location -EA Stop C:\
    try {
      cmd /c dir
    } finally {
      Pop-Location
    }
    

    Another option - assuming that cmd.exe is needed anyway - is to change to the target directory in the context of the cmd /c command, which limits the changed directory to the cmd.exe child process, without affecting the calling PowerShell session:

    cmd /c 'cd /d C:\ && dir'
    

    Finally, you may use Start-Process (the invocation syntax is less convenient), but note that you won't be able to capture cmd's output (unless you redirect to a file with -RedirectStandardOut / -RedirectStandardError):

    Start-Process -Wait -NoNewWindow cmd -ArgumentList '/c dir' -WorkingDirectory C:\