views:

239

answers:

2

I want to do some housekeeping before executing any external console applications (setting some environment vars).

In my web research, it looks like overriding NotifyBeginApplication() in $host might do the trick. Unfortunately, I can't figure out how to do that.

Here's essentially what I want to do...

$host = $host | `
   Add-Member -force -pass -mem scriptmethod NotifyBeginApplication `
   { $env:_startTime = [datetime]::now; $env:_line = $myInvocation.Line }

This doesn't work as $host is constant and it may be the wrong approach anyway.

The documentation that I've been able to find states that this function is called before any "legacy" console application is executed, but another blog entry says that it's only called for console applications that have no I/O redirection.

So, is this the right way to do this? If so, how would I override the function?

If not, how could this be done?

The only alternative I've seen that might work is to fully implement a custom PSHost. That seems possible with existing available source code, but beyond what I want to attempt.

A: 

I also agree with your (unfortunate) conclusion that you will need to create your own custom host to handle this.

You can create additional runspaces easily enough via scripting, but this method isn't accessible in your currently running host (the default console).

Marco Shaw
Maybe an opportunity for the PowerShell group to add a hook to increase the utility of the default console for use with legacy (aka the majority of) applications...?
Roy
I'd post your suggestion here:https://connect.microsoft.com/site/sitehome.aspx?SiteID=99
Marco Shaw
A: 

If this is code that you can modify, then create this function:

Function call {
    ## Set environment here
    $env:FOO = "BAR"
    Invoke-Expression "$args"
}

Now pass your native commands to the call function. Examples:

call cmd /c set
call cmd /c dir
call somefunkyexe /blah -ooo aaah -some:`"Funky Argument`"

If this is code that you can't modify, then things will be complicated.

JasonMArcher
Yes, wrapping individual commands is possible, especially with aliases, but, unfortuantely, the issue is "wrapping" *ALL* external commands. It seems it can't be done as of v2ctp3.
Roy
Well, of course. There is no single point of code that you have access to for the launching of processes except if you (1) create your own host, or (2) create your own single point of code. :)
JasonMArcher