Tuesday, 5 July 2016

How to call a function in a ps1 file from powershell

In Powershell world, the user defined function is one of the easiest way to reuse the set of powershell commands. In some scenarios, this function might be too big, so having functions in separate ps1 file and load a function by importing .ps1 file is a good choice. In this post, I am going to explain how to import a powershell function from ps1 file.

Load Powershell function from ps1 file:

You just imagine the ps1 file MyScript.ps1, and the file contains the following content:
Write-Host "Loading functions"
function MyFunc
{
    Write-Host "MyFunc is running!"
}
Write-Host "Done"
To register the function MyFunc, we need to run the .ps1 file with the dot(.) operator prefix.
 . C:\Scripts\MyScript.ps1
The dot operator is used to include script.
PS C:>  . C:\Scripts\MyScript.ps1
Loading functions
Done

PS C:\> MyFunc
MyFunc is running!

Import Powershell function from psm1 file:

We can also import a function from PSM1 file by using Import-Module command. The major advantage of using Import-Module is that you can unload them from the shell if you need to, and it keeps the variables in the functions from creeping into the shell. First, save the MyScript.ps1 as MyScript.psm1 and load the file by using below command.
Import-Module C:\Scripts\MyScript.psm1
PS C:\> Import-Module C:\Scripts\MyScript.psm1
Loading functions
Done
PS C:\> MyFunc
MyFunc is running!

Advertisements
Advertisements

No comments:

Post a Comment