3

How do I correctly perform includes in Powershell? I have this script:

&  .\config.ps1
&  .\scripts\functions.ps1

Write-Host -f yellow "Saving root site collection"
backupSiteCollection $appURL ($pathDIR + $filesDIR + "\" + $rootSiteCollectionFIL)

Write-Host -f yellow "Saving operation template site collection"
backupSiteCollection ($appURL + $operationTemplateURL) ($pathDIR + $filesDIR + "\" + $operationTemplateFIL)

Write-Host -f yellow "Saving operation template site collection"
backupSolutions $solutionsARY ($pathDIR + $filesDIR)

Write-Host -f yellow "Zipping deployment package"
.\bin\7za.exe a -tzip ".\deploymentPackages\deploymentPackage.zip" "..\deployment"

It actually executes config.ps1 and functions.ps1 (I have echo commands within)m, but it still doesn't recognize my functions:

...loading config.ps1
...loading functions.ps1
Saving root site collection
backupSiteCollection : The term 'backupSiteCollection' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of 
the name, or if a path was included, verify that the path is correct and try again.
6

You can use below snippet to include the Powershell Files into your script.

1) If your required files are in the folder, where your main script lies. Then in main script you can write down below snippet to get the Path.

$ScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

So your main script will look something like below.

# region Include required files
#
$ScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
try {
    . ("$ScriptDirectory\YourFile1.ps1")
    . ("$ScriptDirectory\YourFile2.ps1")
    . ("$ScriptDirectory\YourFile3.ps1")
    . ("$ScriptDirectory\YourFile4.ps1")
}
catch {
    Write-Host "Error while loading supporting PowerShell Scripts" 
}
#endregion

2) If your required files are somewhere else, then your main script will look something like below

try {
    . ("C:\YourFile1.ps1")
    . ("C:\YourFile2.ps1")
    . ("C:\YourFile3.ps1")
    . ("C:\YourFile4.ps1")
}
catch {
    Write-Host "Error while loading supporting PowerShell Scripts" 
}
#endregion
  • A reference to this syntax would be very helpful to include in the answer: . ("$ScriptDirectory\YourFile1.ps1"). – Zingam Mar 10 at 18:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.