PowerShell Live - being retired

Please go to http://www.shelltools.net for more information

Welcome to PowerShell Live - being retired Sign in | Join | Help
in
Home Main Site Blogs Forums Videos Chat Customer Support

call function from another file

Last post 07-31-2007, 2:11 PM by karl. 3 replies.
Sort Posts: Previous
  • call function from another file

     07-30-2007, 7:39 AM

    so is there a way for me to call a function from a different file?

    what i would like to ultimately do is to have a few files with related functions, and then when i write my scripts, i would reference the function from that other file.

    i think it would be like #include <library> for C++

     

    thanks in advance 

  • Re: call function from another file

     07-30-2007, 7:54 AM

    As long as the function has been previously defined and is in the same scope, you can easily do this. I'd recommend simply putting all the functions you want to use in your PowerShell profile. This way they will always be available. A variation, which is probably even a better approach, is to put all your functions in a single script, then dot source that script from within your profile script.  This keeps your profile simple yet you still get all the functions loaded.

    Jeffery Hicks
    Microsoft PowerShell MVP
    SAPIEN Technologies - Scripting, Simplified. www.SAPIEN.com

    blog: http://blog.SAPIEN.com
  • Re: call function from another file

     07-30-2007, 12:12 PM

    ok, im a beginner to powershell,

    how do you dot source the script with all the functions to my profile script? 

  • Re: call function from another file

     07-31-2007, 2:11 PM

    so lets say you have a file called myfunctionlibrary.ps1 and it contains all the functions you want.. well you can then run that file (which as its just definitions of functions) will APPLY them to the current enviroment

    However if you just run it by itself, it will create a new SCOPE, just for that file, then apply them there, and when that file exits you won't have the functions, which defeats your purpose. SO they is a thing in powershell called DOTSOURCING, and it runs something in the CURRENT scope. you simply put a dot before your call so

    . .\myfunctionlibrary.ps1   if you are in the same directory

     Sincerely,

    Karl

View as RSS news feed in XML