Include Relative Files in PowerShell

I would like to include script files with this pseudo-syntax:

Include '.\scripA.ps1' 

But the only thing I found is something like this:

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

what is ugly.

Is there a good way to include scripts with relative paths?

+53
include powershell relative-path
Mar 26 '09 at 1:42
source share
7 answers

Unfortunately no, there is no good way. PowerShell does not support this idea very well in V1. Indeed, the approach you take is the best approach

+11
Mar 26 '09 at 1:44
source share
— -

You can use the $ PSScriptRoot parameter as follows:

 . "$PSScriptRoot\script.ps1" 
+99
Nov 26 '13 at 11:42
source share

You can use the dot-source (include) file:

.. \ ScriptA.ps1

To get the full path to the script:

Solve the path. \ ScriptA.ps1

+29
Mar 26 '09 at 9:45
source share

Dot-sourcing is the easiest option, although not very beautiful, as already mentioned. However, this format makes it a little cleaner:

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

In addition, a note on relative paths , which is useful for explicit: the original message may seem desirable for a path relative to the current working directory; in fact, the intent should relate to the current source directory of the script (as the alex2k8 native code example shows). Thus, this allows the current script to access other scripts from the same repository.

+20
Jun 02 '11 at 17:19
source share

Starting with V2 (native starting with Win7 / 2008R2; see $psversiontable.psversion ), you can easily include a file, for example, like this:

 . "RelativeOrAbsolutePathToFile\include.ps1" $result = FunctionInIncludeFile() 

Link:
How to Reuse Windows PowerShell Features in Scripts

+6
Mar 22 '13 at 9:05
source share

This will probably work from any directory, but it will sloooooowwwww find if your source directory is not a direct antecedent of the directory of the file you are trying to include. IOW, if the starting point for this search is the root of c: \ or another drive letter, this is likely to be terribly slow.

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

This will work especially well if you are developing scripts on your PC, but you need to deploy them to a server that will run the script as a scheduled task.

0
Nov 18 '17 at 15:09 on
source share

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

0
Aug 14 '19 at 17:51
source share



All Articles