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.

I’m an IT professional who has worked for distributers and several MSP’s for over 15 years. My main focus is on the Microsoft Cloud but have a deep knowledge in Exchange, Active Directory and core Windows infrastructure. I’m a lover of craft beer and going to live music events. I’m also on a mission to slowly make my home smarter.

You may also like

How To: Remove OAuth Credentials when removing Exchange
Removing the last Exchange server but OAuth service principal creds wont remove. Here's what’s wrong and how to fix it....
Yes No Choice Function in PowerShell
This article explores a PowerShell function that simplifies user prompts using the $host.ui.PromptForChoice method. By restricting input to predefined options, the function ensures accuracy and ease of use. It returns 0 for No and 1 for Yes, with customizable parameters for the prompt's title, message, and default selection....