Search
Close this search box.
Programming code abstract technology background of software developer and  Computer script

Get Execution Path of Script

I have been writing a script which generated a report. I had used Out-File to write to a file and this had been working as expected for some time. Today however, I opened up PowerShell and entered the path of the script without changing directory to the script location first. This caused the report file to be written to a directory other than the script itself. I quite like having the report and script in the same directory as it keeps it all together. So I thought, how do I insure the script writes the report file where it’s being run from. The solution is actually pretty simple.

				
					$fullPathIncFileName = $MyInvocation.MyCommand.Definition
$currentScriptName = $MyInvocation.MyCommand.Name
$currentExecutingPath = $fullPathIncFileName.Replace($currentScriptName, "")

$outfilename = $currentExecutingPath + "Report.txt"

Get-Date | Out-File -Append $outfilename
				
			

As you can see the sollution is very simple but effective. I’ll be using it future PowerShell scripts I write so thought I’d write an article on the subject in case it helps someone out.

You may also like