I want to call a Batch file from a PowerShell script. This Batch file calls another Batch file which resides in the same directory. The PowerShell script is in a different directory. For example consider this files/directories:
C:
+-- Test
+-- Batch
+ -- Foo.bat
+ -- Bar.bat
+-- PS
+-- Foo.ps1
Foo.bat simply calls Bar.bat:
call Bar.bat
And in Foo.ps1 I'm calling Foo.bat:
Set-Location "C:\Test\Batch"
Invoke-Item "Foo.bat"
My problem now is, that Foo.bat gets called but still uses C:\Test\PS as its working directory and therefore cannot find Bar.bat. How can I force Foo.bat to use C:\Test\Batch as its working directory?
Neither changing Foo.bat nor putting Foo.ps1 in the same directory as Foo.bat are options.
call /?and read the output usage help. Argument 0 is always the string used to start the processing of a batch file. It isFoo.batandBar.batin your examples. There can be used inFoo.batthe command linecall "%~dp0Bar.bat"to reference the batch fileBar.batwith full path of the currently processed batch fileFoo.bat.%~dp0references the full path of the currently processed batch file which always ends with a backslash.cmd.exeis.cmd. The file extension.batis still supported but should not be used nowadays anymore. The file extension.batis for batch files processed byCOMMAND.COMof MS-DOS and Windows 95/98/ME. The Windows Command Processor processes batch files with file extension.bata very little bit different to batch files with file extension.cmd. See: Windows batch files: .bat vs .cmd?FORcommand a lot. They always said that Microsoft wanted to do away with EXE files, but to this day it has never done away with COM files (chcp, format, mode, etc.). They still exist in Windows 11 24H2! I've always used%~dp0for both BAT and CMD, and I agree that the file should have the CMD extension, but the poster was clear: Neither changing Foo.bat, so you can't change it to CMD and you can't have%~dp0.