Search code examples
powershelldot-source

Dot-source file from different locations


I'm dot-sourcing a "function library" file into every Powershell script I'm working on.

Currently, I'm putting this file in the same directory as the script and dot-sourcing it as follows:

. (Join-Path $PSScriptRoot FunctionLibrary.ps1)

This is fine once the script goes "into production", on a server in a specific location relevant to what the script is doing. However, when I'm building the scripts from my generic "Powershell" folder on my network drive, this means I'm ending up with the same file in a few different folders - it's just a matter of time before I edit one functions library then make a different edit to a different file and end up with myriad versions of what should be the same file.

Ideally therefore I'd like to store this function library file in "G:\PowerShell\Function Library" and reference it if such a file doesn't exist in the script's working directory.

The pseudo for this would be something like:

If( File Exists in C:\Location ) {
    Load C:\Location\File
}
ElseIf( File Exists in "This Directory" ) {
    Load "This Directory"\File
}
Else {
    Log "Unable to load functions library, exiting"
    Exit
}

To achieve this right now, I'm simply doing:

. (Join-Path $PSScriptRoot FunctionLibrary.ps1)
. "G:\Powershell\Function Library\FunctionLibrary.ps1"

This works, but always gives me an error - and I can't work out a way to silence the error. I've tried -ErrorAction "SilentlyContinue" and | Out-Null but neither appear to make a difference.

I guess there are therefore two potential answers to this question, and perhaps answering them both would be good for future readers of this thread:

  • How do I test for the existence of a file (Test-Path presumably?) and then dot-source it if it exists?
  • How do I dot-source a file in Powershell and ignore any errors from files that can't be found?

Thanks in advance. P.S. if any moderators want to describe a more relevant title, please feel free - I've tried and failed!


Solution

  • You've basically answered you're own question there, just needed to follow through on your line of thinking regarding Test-Path. By testing the availability of your file before trying to dot-source it, you won't end up with any errors (the error being that you were trying to dot-source a file that doesn't exist.)

    Here's a tweaked version of your pseudo code:

    if (Test-Path -Path 'C:\Location\file.ps1') {
        . 'C:\Location\file.ps1'
    }
    elseif (Test-Path -Path "$PSScriptRoot\file.ps1") {
        . "$PSScriptRoot\file.ps1"
    }
    else {
        Write-Warning -Message 'file.ps1 not found'
    }