Here’s a code snippet that forcefully closes all open documents in the PowerShell ISE. Be aware: it closes all documents without asking to save. This can be useful if you goofed around and have no intention to save your scripts:

foreach ($tab in $psise.PowerShellTabs)
{
    $files = $tab.Files
    foreach ($file in $files)
    {
        $files.Remove($file, $true)
    }
}

When you run this, you will receive an error, though. Even if you don’t use PowerShell ISE, this error (and its remedy) may be interesting to you.

The code enumerates all open files and tries to close one file after another. This does not work: you cannot change an array while you enumerate it. So whenever PowerShell ISE closes a document, the list of files is changed, and this breaks the loop.

Whenever this occurs, a simple workaround is to copy the array to another array first. Then you can safely enumerate the copied array.  Copying an array is as simple as casting it to [Object[]].

Here is the correct code:

foreach ($tab in $psise.PowerShellTabs)
{
    $files = $tab.Files
    foreach ($file in [Object[]]$files)
    {
        $files.Remove($file, $true)
    }
}

Are you an experienced professional PowerShell user? Then learning from default course work isn’t your thing. Consider learning the tricks of the trade from one another! Meet the most creative and sophisticated fellow PowerShellers, along with Microsoft PowerShell team members and PowerShell inventor Jeffrey Snover. Attend this years’ PowerShell Conference EU, taking place April 17-20 in Hanover, Germany, for the leading edge. 35 international top speakers, 80 sessions, and security workshops are waiting for you, including two exciting evening events. The conference is limited to 300 delegates. More details at www.psconf.eu.

Twitter This Tip! ReTweet this Tip!

Anonymous