Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run cmd from a given folder inside PowerShell script

Tags:

powershell

cmd

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!

like image 676
user1692315 Avatar asked Oct 24 '25 10:10

user1692315


1 Answers

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:

  • In Windows PowerShell and PowerShell (Core) 7 version up to 7.3.x, an external program such as cmd.exe cannot produce a script-terminating (fatal) error (except potentially - in Windows PowerShell, due to a bug - when a 2> redirection is involved), so Pop-Location is guaranteed to run.

  • However in PowerShell 7.4+ it is now possible for external-program calls to trigger script-terminating errors, namely by setting the $PSNativeCommandUseErrorActionPreference preference variable to $true as well as the $ErrorActionPreference preference variable to 'Stop'.

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:\
like image 145
mklement0 Avatar answered Oct 26 '25 06:10

mklement0