function working in PSH ISE, not in PSH console

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of John Mooper John Mooper 1 year, 2 months ago.

  • Author
  • #27951
    Profile photo of John Mooper
    John Mooper

    Hi. I have a .ps1 script which defines a function.
    When I run that script in ISE, that function is added to the functions list (dir function:\) and I can use it in the ISE console just fine.
    However when I start a regular PSH console session (powershell.exe), run the .ps1 script (dot-source it actually), I can't use the function and it's not added to the list (dir function:\)

    This is a first time something like this happened to me. Any idea what could be the problem?

    Thanks in advance

  • #27952
    Profile photo of Don Jones
    Don Jones

    This isn't a "problem," is just the way the two environments are designed. The ISE maintains a consistent scope to facilitate testing.

    In the console, when you run a script, the function is defined – but it goes away when the script ends. This is absolutely by design. The correct approach is to build your script as a script module (.PSM1), which you can load by using Import-Module and unload by using Remove-Module. Doing so "keeps" the function while the module is loaded. Dot-sourcing is (more or less) a v1 technique that's not as flexible as script modules.

    This is all in "Learn PowerShell Toolmaking in a Month of Lunches," if you're interested :).

  • #27957
    Profile photo of John Mooper
    John Mooper

    Thanks for replying Don.
    It was probably my confusion since I work in ISE most of the time and didn't realize how it works outside of it.

You must be logged in to reply to this topic.