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.
Avoid using the Invoke-Item
cmdlet to execute commands. Use the Start-Process
cmdlet instead.
The problem is that the working folder is not defined. There are several ways to define this. Using the Start-Process
cmdlet is the most appropriate for this specific case.
$Result = Start-Process -FilePath 'cmd.exe' -ArgumentList '/c Foo.bat' -WorkingDirectory 'C:\Test\Batch' -Wait -PassThru
Write-Output -InputObject "code $( $Result.ExitCode )"
The Wait
and PassThru
arguments will be required if you want to check the exit code.
I used an online translator. I apologize for not being fluent in the language.