Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

When working in a regular PowerShell console, variables created within a script will be automatically cleared out when the script terminates unless they are elevated to a greater scope. However, this appears to not be the case within the console in the PowerShell ISE. After I've run a script, its variables persist even though they should by default be confined to the scope of the script.

So far, the only way to clean this up that I've seen is to add a lot of rv lines at the end of my scripts which will be unnecessary when the script is run normally within PowerShell. I've also got to remember to run rv any time that I run a snippet of the script unless I actually want the variables to persist longer in the session.

Is there any way to configure PowerShell ISE to work more like an actual PowerShell console in this regard?

share|improve this question

1 Answer 1

There is a problem with F5 - it's not really running your script, it's dot-sourcing it. I've created function + separated key binding to walk around. It's a part of bigger project I used work on (ISEFun on codeplex). Shorter version (that will save existing script and convert "untitled" to script block):

$InvokeScript = {
    if ($file = $psISE.CurrentFile) {
        if (Test-Path $file.FullPath) {
            if ($file.FullPath -match '\.ps1$') {
                if (! $file.IsSaved) {
                    $file.Save()
                }
                # Script - we run it...
                & $file.FullPath
            }
        } else {
            & ([scriptblock]::Create($file.Editor.Text))
        }
    }
}

$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add(
    "Invoke script",
    $InvokeScript,
    'F4'
)

From now you can use F4 instead of F5 and keep your session clean. To get it every time you can simply add it to your $profile script.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.