function working in PSH ISE, not in PSH console

Welcome Forums General PowerShell Q&A function working in PSH ISE, not in PSH console

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
3 years, 2 months ago.

  • Author
    Posts
  • #27951

    Participant
    Points: 0
    Rank: Member

    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

    Keymaster
    Points: 1,524
    Helping HandTeam Member
    Rank: Community Hero

    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

    Participant
    Points: 0
    Rank: Member

    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.

The topic ‘function working in PSH ISE, not in PSH console’ is closed to new replies.