Calling Functions

This topic contains 5 replies, has 4 voices, and was last updated by  Stuart 4 months, 2 weeks ago.

  • Author
    Posts
  • #67551

    Stuart
    Participant

    Hi Guys,

    Is there a simple way to call a function within a function?

    I have written a module with 8 functions within it. For most functions they have to connect to either Exchange On Premise or Exchange Online.

    Rather than have to put the code in each function to connect to Exchange, is there a way to make the connection to Exchange into a function then call it when needed throughout the script?

    Many Thanks

  • #67557

    Cyril Muffat
    Participant

    If u have built a module just put the exchange connect function at the top and u can call ur connect-exchange function in any function within the module

    When u ll load ur module from shell ur connect-exchange function ll be load as well so any call to this function is possible

    • #67605

      Stuart
      Participant

      Of course! why didnt I think of that. Thanks

  • #67558

    Not sure if this is the proper way of going about it, but for a function I built to run in another script, I started the script with Import-Module and the function's location (So something like "Import-Module C:\Function-Name.ps1"), then called the function later in the script.

  • #67564

    Aaron Hardy
    Participant

    To elaborate on what Cyril said, you could do something like this (bypassing params, etc. for brevity):

    Function Connect-ExchangeOnline {
        # Make connection to EO
    }
    
    Function Connect-ExchangeOnPrem {
        # Make connection to on-prem
    }
    
    Function Get-LicensedUser {
        Connect-ExchangeOnline
    
        # code
    }
    
    Function DoSomethingOnPrem {
        Connect-ExchangeOnPrem
    
        # code
    }
    

    And so on... The key is to have the Connect-Exchange* function(s) declared before any other functions that call it/them.

    • #67606

      Stuart
      Participant

      Thanks for this too. I think Cyril was suggesting that youd connect to Exchange before defining any of the functions in the module. Then the commandlets would just be there to use. Not tried it, but sounds like either way could work

You must be logged in to reply to this topic.