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?
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.
The way around this seems to be using a complete path to the second script:
. (Join-Path -Path $PSScriptRoot -ChildPath 'SecondScript.ps1')
@Theo has a useful workaround, but the cause is that []
must be escaped in paths.
$path = 'C:\path\`[to`]\script.ps1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With