Shared function in PowerShell scripts - Advanced Installer Community
hsc
Posts: 117
Joined: Wed Mar 02, 2016 2:55 pm

Shared function in PowerShell scripts

I have a few PowerShell scripts in my installer projects. Many scripts contain identical code, such as functions that evaluate the validity of user input. Rather than defining this function separately in each script, I'd prefer to store them in a central location which can be accessed (e.g. dot-sourced) by the various scripts which want to call these functions.

Additional details:
  • Some (short) scripts are inline, but longer and more complex scripts are contained in separate files.
  • The scripts should not be installed to the target system. They are only used during installation.
Any ideas?

Thanks
Hans
Catalin
Posts: 7849
Joined: Wed Jun 13, 2018 7:49 am

Re: Shared function in PowerShell scripts

Hello Hans,

Usually, in PowerShell, that is achieved through modules.

For more information about this, please refer to the following:

about_Modules

You could try having the reusable functions as modules and then importing them in your other scripts.

To be fully honest with you, I haven't tested this so I do not know whether this will work or if we will face some possible corner cases.

Best regards,
Catalin
Catalin Gheorghe - Advanced Installer Team
Follow us: Twitter - Facebook - YouTube
hsc
Posts: 117
Joined: Wed Mar 02, 2016 2:55 pm

Re: Shared function in PowerShell scripts

Hi Catalin,

thank you for this suggestion. I am afraid it doesn't work in my situation. If I understand modules right, a module must exist as a disk file before it is used. But in my situation, the script runs during the UI phase of the installer, so the installer hasn't copied anything to disk yet. Besides, I don't want the script and its modules to be left on the target system.

I may create a solution outside Advanced Installer, something that concatenates chunks of script code into a script file before the script file is imported into the installer project.

May anyone from the community can comment?

Regards
Hans
Catalin
Posts: 7849
Joined: Wed Jun 13, 2018 7:49 am

Re: Shared function in PowerShell scripts

Hello Hans,

You are always welcome!
If I understand modules right, a module must exist as a disk file before it is used.
This is indeed true. The module would have to be imported in the current PowerShell session.
But in my situation, the script runs during the UI phase of the installer, so the installer hasn't copied anything to disk yet.
To overcome this, we could make use of temporary files.
Besides, I don't want the script and its modules to be left on the target system.
Temporary files could help here as well, since they are automatically removed at the end of the installation, unless told otherwise.

Best regards,
Catalin
Catalin Gheorghe - Advanced Installer Team
Follow us: Twitter - Facebook - YouTube

Return to “Common Problems”