If you want to execute a function from another PowerShell script file, you can “dot-source” the file.

The “.” is a special operator in PowerShell that can load another PowerShell script file en import all code in it.

 

Assume both PowerShell scripts are in the same folder, we can use the code in script1.ps1 in script2.ps1 in the following way:

 

PowerShell script1.ps1

 

function ReturnGivenText {

Param(

        [Parameter(Mandatory=$True)]

        [string]$text

    )

    return $text

}

 

PowerShell script2.ps1

$text = ReturnGivenText -text “Hello world”

write-host $text

 

This will output:

Hello world

 

Note: I use the PowerShell >3 global variable $PSScriptRoot, to make the relative path, absolute, so we can use the “.” operator.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.