Author Posts

March 29, 2017 at 3:48 pm

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

March 29, 2017 at 5:04 pm

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

March 29, 2017 at 5:17 pm

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.

March 29, 2017 at 5:49 pm

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.

March 30, 2017 at 3:53 pm

Of course! why didnt I think of that. Thanks

March 30, 2017 at 3:55 pm

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