Recently I have been trying to do almost everything in Powershell. With the release of Powershell V2 RC and the awesome visual debugger that comes with Powershell called Powershell ISE, I have a Powershell window open at all times. I am getting my google calendar events form command line, doing recursive ftp uploads and download as well. Now I have started to even do outlook automation with PS.
The Problem
Any slightly efficient developer would write functions and reuse them later. So I tended to write functions add kept on adding them to my Powershell profile file. After a while that turned a little messy and hard to manage. So now I thought why don’t write different script files put my functions in there and use them when needed. So I created functions for Google Data API, Outlook functions. Now when I call them from the prompt, after execution of the script the functions are no longer there. It is because the scriptblock runs in a different execution context and after execution the context is removed. So the functions I have put the file no longer exist when I call them.
For example I have written a function in myfunc.ps1 to convert string into base64 string which looks like this
function tobase64 ( $asciistring )
{
return [Convert]::ToBase64String([System.Text.Encoding]
::ASCII.GetBytes($asciistring))
}
Now after running the script .\myfunc.ps1 when I call the function, it no longer works.
Solution
After running around the internet for hours, looking for a solution to run scripts in the same executions context and trying out several different approaches, I was about to give up. Then I found the worlds easiest solution in Donn Felkers blog. All you need to do is to add a simple dot ( “.” ) at the start of the line to make it run the in the same context.
So if you were running the script like this,
.\myfunc.ps1 or c:\somefolder\myfunc.ps1
You should run it like this
. .\myfunc.ps1 or . ‘c:\somefolder\myfunc.ps1’
See the added dot? That does the trick. I wish this was advertized more, then I wouldn’t have had to search for hours to find a solution.


Hi,
Sorry it took so long to find the 'trick'. Its pretty well known for those who know it. Lame, I know.
What keywords did you search for? Its documented in
Get-Help about_scopes
Cheers,
Ibrahim
Posted by: Ibrahim Abdul Rahim | June 03, 2009 at 03:49 AM
I searched with the web with my blog entry title, "Executing Powershell Scripts in the Same Execution Context". Since I could not get anything ... I wrote this down as a blog entry so that people like me who searches with the same keywords finds the answer.
yep ...pretty lame.
Posted by: Shafqat Ahmed | June 03, 2009 at 04:41 AM