Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including a script does not work when path has special characters

I am trying to include a script inside another which is in the same folder, using the dot syntax:

. '.\BaseScript.ps1'

The path to the scripts has a folder with square brackets in the name. Even though I am using relative paths, the path error still occurs.

Moving it to some other path without special characters in the name works fine.

How can such a case be catered while using relative paths?

like image 267
Umair Ahmed Avatar asked Aug 11 '21 14:08

Umair Ahmed


3 Answers

Unfortunately, PowerShell treats the operands to the . dot-sourcing and & call operators (which includes implicit invocation[1] ) as wildcard expressions, which causes problems with paths that contain [, which is a wildcard metacharacter.

The solution is to escape the [ as `[; e.g., to dot-source a script whose path is ./test[1]/script.ps1:

# Note: '/' and '\' can be used interchangeably in PowerShell.
. ./test`[1]/script.ps1

Important: If the path is relative, it must start with ./ or .\ (see below for full paths).

Note: [ is a wildcard metacharacter, because you can use it to express character ranges ([a-z]) or sets ([56]); while ] is clearly also needed, it is sufficient to escape [.

This unfortunate requirement, which also affects other contexts, is the subject of GitHub issue #4726.


Alternatively - and bizarrely - as Theo's helpful answer shows, the need for this escaping goes away if you use a full path.

# Dot-source 'script.ps1` from the same location as the running
# script ($PSScriptRoot).
# (Use $PWD to refer to the *currrent* dir.)
# Because this results in a *full* path, there is no need to escape, strangely.
. $PSScriptRoot/script.ps1

[1] &, which can invoke any command and runs commands written in PowerShell code in a child scope, isn't strictly needed for invocation; e.g. & ./path/to/script.ps1 and ./path/to/script.ps1 are equivalent; however, & is required if the path is quoted and/or contains variable references - see this answer.

like image 58
mklement0 Avatar answered Nov 01 '22 18:11

mklement0


The way around this seems to be using a complete path to the second script:

. (Join-Path -Path $PSScriptRoot -ChildPath 'SecondScript.ps1')
like image 20
Theo Avatar answered Nov 01 '22 16:11

Theo


@Theo has a useful workaround, but the cause is that [] must be escaped in paths.

$path = 'C:\path\`[to`]\script.ps1'
like image 29
Bender the Greatest Avatar answered Nov 01 '22 18:11

Bender the Greatest