如何在PowerShell中运行子目录可执行文件并使其识别自身配置文件
Solution
The key issue here is that when you run an executable from a parent directory, its working directory defaults to your current location (the main folder), so it will look for asdf1.txt/asdf2.txt in main instead of their respective subfolders. To fix this, you need to launch each executable with its own subfolder as the working directory.
Option 1: Run Sequentially (One After the Other)
Use Push-Location to switch to each executable's folder, run it, then switch back to the main directory:
# Run exe1 from its own folder Push-Location .\exe1Folder .\exe1.exe --config asdf1.txt Pop-Location # Run exe2 from its own folder Push-Location .\exe2Folder .\exe2.exe --config asdf2.txt Pop-Location
Push-Locationtemporarily changes your working directory to the target subfolder, andPop-Locationreverts it back tomainafterward.- This guarantees each executable looks for its config file in the correct subfolder instead of the parent directory.
Option 2: Run in Parallel (At the Same Time)
If you want both executables to run simultaneously, use Start-Process with the -WorkingDirectory parameter to set the correct context for each:
# Launch exe1 in its working directory (runs in the same console window) Start-Process -FilePath ".\exe1Folder\exe1.exe" -ArgumentList "--config asdf1.txt" -WorkingDirectory ".\exe1Folder" -NoNewWindow # Launch exe2 in its working directory Start-Process -FilePath ".\exe2Folder\exe2.exe" -ArgumentList "--config asdf2.txt" -WorkingDirectory ".\exe2Folder" -NoNewWindow
- Add the
-Waitparameter to either line if you want PowerShell to pause until that executable finishes before moving on. - Omit
-NoNewWindowif you prefer each process to run in its own separate console window.
Why This Works
By setting the working directory to each executable's subfolder, the relative path asdf1.txt in the --config argument resolves to the file inside exe1Folder instead of the main directory. Without this adjustment, the executable would fail to locate the config file because it's searching in your current working directory by default.
内容的提问来源于stack exchange,提问作者docchang

