If I run it with right-click in the explorer and run it with “Run with powershell” it runs fine. However, if I want to run it in either as a batch file or from another program using “powershell.exe currentDir.ps1”. This doesn’t work as powershell doesn’t start in the current directory and can’t find the file. Any idea how I can make it work?
Cheers
Renger
I want to run the script so I can parse the current directory to my other external program I wrote (otherwise I have to set it in the program itself and if the directory changes, I have to adjust this manually).
I tried this powershell.exe .\myscript.ps1 and that did the trick
Thanks
Renger
If I understand your scenario correctly, you have …
A batch/cmd file that call PowerShell
A PowerShell script to return the current directory
Another call in your batch/cmd file to a program, where you need the path returned from the PowerShell script
If all you are after is the current directory of your batch/cmd file, you really don’t need PowerShell at all. Instead look into the special “%~dp0” variable. This is basicly the same as the $PSScriptRoot variable in PowerShell 3 and later versions (beware that this variable is only populated when running a script.
Consider these examples …
CMD script:
@echo off
cls
echo Script file is in: %~dp0
echo Current directory: %cd%
pause
echo Push location to script dir
pushd %~dp0
echo Current directory: %cd%
pause
echo Pop location (back to where we came from)
popd
echo Current directory: %cd%
PowerShell script:
Clear-Host
Write-Host "Script file is in: $PSScriptRoot"
Write-Host "Current directory: $(Get-Location)"
Pause
Write-Host 'Push location to script dir'
Push-Location $PSScriptRoot
Write-Host "Current directory: $(Get-Location)"
pause
Write-Host 'Pop location (back to where we came from)'
Pop-Location
Write-Host "Current directory: $(Get-Location)"
I just wanted to thank you for explaining that well. I’m a batch file guy and I’m new to powershell, trying to learn powershell. This explains it very well.