Tag Archives: ps2exe

This blog post proposes a consistent method of obtaining the current working directory using PowerShell, whether your scripts are embeded inside an executable or not.

Obtaining the Current Working Directory using PowerShell

I tend to use a great tool called PS2EXE to compile my PowerShell scripts into executables. And sometimes I need to put some dependency DLLs in the same folder as my compiled exe, and reference them using code such as:

Add-Type -Path [PathToDll]

To add the reference to the DLLs that reside in my executable folder, I need to somehow deduce the current ‘working’ directory.

This is easy to do when just running a PS1 script directly – I won’t bore you with that. But the trouble with wrapping your PowerShell scripts inside an executable is that the ‘typical’ methods of obtaining the working/script directory don’t work. They either return the wrong path (“c:\windows\system32”, “c:\windows\system32\WindowsPowerShell\v1.0\”, “c:\windows\temp” etc) or return no path at all!

There are a few reasons for this. One could be the context you are running it from (i.e, you’re not double-clicking it but instead running it from the ‘Run’ key in the registry with no context). And also because perhaps the compiled executable runs your ‘wrapped’ PowerShell script in-memory, or it puts a copy in the %temp% location and runs it from there (hence it doesn’t matter where the executable physically exists on disk).

Coupled with this, some methods of obtaining the script/exe directory wouldn’t work in either the PowerShell console, the PowerShell ISE, or the compiled executable! And I wanted one approach that worked for all.

The only method that worked for me (and I stole this code from here) was:

Welcome to our Blog

"Welcome to our blog. We hope to share tips, scripts, tutorials and tool sets which will assist other professionals in creating more robust application packages and scripts, as well as automating and streamlining common processes."