Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

Dot-sourcing is the simplest option albeit not particularly pretty, as already stated. However, this format makes it just a tad bit cleaner:

$ScriptDirectory = Split-Path $MyInvocation.MyCommand.Path
. (Join-Path $ScriptDirectory ScriptA.ps1)

Also, a note about relative paths that is useful to make explicit: the original post might seem to imply wanting a path relative to the current working directory; in reality the intention is to be relative to the current script's source directory (as alex2k8's own code sample indicates). Thus, this allows the current script to access other scripts from the same repository.

As of V2 (native starting with Win7/2008R2; see $psversiontable.psversion) you can easily include a file like so:

. "RelativeOrAbsolutePathToFile\include.ps1"

$result = FunctionInIncludeFile()

Reference:
How to reuse windows powershell functions in scripts

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.

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')

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top