tags:

views:

100

answers:

2

hi all, i wanted to automatically open the last opend files in ISE with posh script, so i tryed to save filepaths of these files like the following.

$action = { $psISE.CurrentPowerShellTab.Files | select -ExpandProperty FullPath | ? { Test-Path $_ } |
Set-Content -Encoding String -Path$PSHOME\psISElastOpenedFiles.txt
Set-Content -Encoding String -Value "Now exiting..." -Path c:\exitingtest.log
}
Register-EngineEvent -SourceIdentifier Exit -SupportEvent -Action $action

when i close ISE, exitingtest.log is created and has "Now exiting...", but psISElastOpenedFiles.txt isn't created. it seems that ISE closes all opening files before the exiting event is executed.

should i use Timer event?

+1  A: 

I tried to do this a few months ago and discovered that a race-condition prevents this from working 95% of the time. The tab collection in ISE's object model is generally disposed of before the powershell.exiting event is handled. Dumb, yes. Fixable, no.

-Oisin

x0n
+2  A: 

Rather than saving on exit, save the MRU info when the CurrentTabs and Files objects raise the CollectionChanged event. This is the MRU ISE addon I'm using:

# Add to profile
if (test-path $env:TMP\ise_mru.txt)
{
    $global:recentFiles = gc $env:TMP\ise_mru.txt | ?{$_}
}

else
{
    $global:recentFiles = @()
}

function Update-MRU($newfile)
{
    $global:recentFiles = @($newfile) + ($global:recentFiles -ne $newfile) | Select-Object -First 10

    $psISE.PowerShellTabs | %{
        $pstab = $_
        @($pstab.AddOnsMenu.Submenus) | ?{$_.DisplayName -eq 'MRU'} | %{$pstab.AddOnsMenu.Submenus.Remove($_)}
        $menu = $pstab.AddOnsMenu.Submenus.Add("MRU", $null, $null)
        $global:recentFiles | ?{$_} | %{
            $null = $menu.Submenus.Add($_, [ScriptBlock]::Create("psEdit '$_'"), $null)
        }
    }
    $global:recentFiles | Out-File $env:TMP\ise_mru.txt
}

$null = Register-ObjectEvent -InputObject $psISE.PowerShellTabs -EventName CollectionChanged -Action {
    if ($eventArgs.Action -ne 'Add')
    {
        return
    }

    Register-ObjectEvent -InputObject $eventArgs.NewItems[0].Files -EventName CollectionChanged -Action {
        if ($eventArgs.Action -ne 'Add')
        {
            return
        }
        Update-MRU ($eventArgs.NewItems | ?{-not $_.IsUntitled}| %{$_.FullPath})
    }
}

$null = Register-ObjectEvent -InputObject $psISE.CurrentPowerShellTab.Files -EventName CollectionChanged -Action {
    if ($eventArgs.Action -ne 'Add')
    {
        return
    }
    Update-MRU ($eventArgs.NewItems | ?{-not $_.IsUntitled}| %{$_.FullPath})

}

Update-MRU
Keith Hill