Include relative files in PowerShell

Viewed 69544

I would like to include script files with such pseudo syntax:

Include '.\scripA.ps1'

But the only thing I have found is some thing like this:

$thisScript = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
. ($thisScript + '.\scriptA.ps1')

that is ugly.

Is there some nice way to include scripts with relative paths?

7 Answers

You can utilize the $PSScriptRoot parameter like this:

. "$PSScriptRoot\script.ps1"

You can dot-source (include) the file:

. .\scriptA.ps1

To get the full path of the script:

Resolve-Path .\scriptA.ps1

Unfortunately no, there is no good way. PowerShell doesn't really support this idea very well at all in V1. Really the approach you are taking is the best approach

You can use $PSScriptRoot and the "Split-Path" directive to make it work cleanly for relative paths. . (($PSScriptRoot | Split-Path | Split-Path)+'somedir\ps\script.ps1')

This would probably work from any directory, but it'll be a sloooooowwwww find if your starting directory is not a direct antecedent directory of the file you're trying to include. IOW, if your starting point for this search is the root of c:\ or some other drive letter, this will probably be horrifically slow.

. $(Resolve-Path -literal $(gci -Recurse include.ps1))

This will work particularly well if you're developing scripts on your PC but need to deploy them to a server that's going to run the script as a scheduled task.

Related