4

When writing a powershell script in ISE I have something analogous to (which I execute with F5):

Function DoSomethingNow
{
    "What am I doing?"
}

DoSomethingNow

The problem is if I rename or remove DoSomethingNow it is still available in the session. This causes confusion in that my script will continue to work, whereas I would expect an error in the absence of the function.

I can only assume I need to clear the session after each round of debugging, however it would appear this is only possible by restarting ISE (therefore restarting the powershell session).

Therefore I ask:

  • Is it possible to clear the session so that DoSomethingNow is no longer in scope?
  • What is the 'correct' way to debug and execute powershell scripts repeatedly?
  • Perhaps I'm not using ISE the correct way?

I'd appreciate being pointed in the right direction.

m.edmondson
  • 30,382
  • 27
  • 123
  • 206
  • possible duplicate of [Is it possible to reset the runspace in Powershell ISE?](http://stackoverflow.com/questions/7338395/is-it-possible-to-reset-the-runspace-in-powershell-ise) – alroc Apr 30 '13 at 15:48

1 Answers1

3

You can "delete" the function with Remove-Item and the Function PSDrive

Remove-Item Function:\DoSomethingNow

If you add this to the end of your script & remove each function (only in debug situations, I hope), you'll get a fresh start each time. You can do similar for aliases & environment variables, if you're setting those.

You may also want to look at $Error.Clear() to clear out any entries in the $Error object, as well as Remove-Variable (you can probably guess what this one does).

alroc
  • 27,574
  • 6
  • 51
  • 97
  • Perhaps I'm thinking about this the wrong way, but it seems a hassle to have to clear everything up like this? Has .net become to ingrained in me? Also why would you only clear these out in debug situations? – m.edmondson Apr 30 '13 at 15:17
  • It's not so much .Net vs. Powershell (since PoSH *is* .Net) as it is compiled program vs. console session/environment. When you exit a compiled program, everything about its state that isn't persisted elsewhere evaporates. Within a console session, everything you do sticks around until you clear it, or kill the whole session - you're working *within* a compiled program, in a way. – alroc Apr 30 '13 at 15:20
  • So why isn't there a decent way to clear sessions at the end of your script? Am I approaching scripting development incorrectly? – m.edmondson Apr 30 '13 at 15:22
  • Have a look at [this SO post on the same subject](http://stackoverflow.com/questions/7338395/is-it-possible-to-reset-the-runspace-in-powershell-ise). Other script IDEs can do it, but it's not a native feature of the ISE. – alroc Apr 30 '13 at 15:47