Split-Path -Parent $MyInvocation.MyCommand.Path | Out-File -Encoding Default test.R
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?
The $MyInvocation.MyCommand.Path is used to pass the current path during a script.
Why are you collecting the current directory ? Does it contain something you need to reference ?
Powershell.exe has a list of syntax's to use. If you do "PowerShell /?" you will get a list and some help information. The first part looks like this:
PowerShell[.exe] [-PSConsoleFile | -Version ]
alternatively you could use
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).
If I understand your scenario correctly, you have ...
* A batch/cmd file that call PowerShell
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 ...
@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%
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. 🙂
You must be logged in to reply to this topic.