LesFerch
LesFerch

Reputation: 1995

How to run a PowerShell command line from within a folder that has a name that contains a single left bracket

Here is a screen shot of the issue. You can see that I'm in a folder named C:\Test[ and I get an error when attempting to run Test.ps1 via a PowerShell command line: enter image description here

Using an absolute file name doesn't make any difference: enter image description here

I also tried escaping the bracket with a backtick, but had no luck with that. enter image description here

Of course, in this simple example, I can just run .\Test.ps1 directly, but this is part of a bigger issue where a PowerShell script is run from an HTA which could be located in a folder that contains a left bracket, right bracket, or both. Different issues occur depending on the combination. It would be too confusing to show all permutations in one question, so I'm starting with this one, as it is the simplest to demonstrate.

My current "solution" is to display an error message if the user is attempting to run the HTA from a directory that contains left or right brackets, but I'd prefer to find a way to make it work.

I've read through various articles regarding square bracket folder names and PowerShell, but they all refer to using "-literalpath" or backticks within a PowerShell script and the only command line reference I found said to use "-file" which, of course, I'm already using.

That was this article: Cannot run PowerShell script in folder with square braces

The answers provided in that article don't work for a folder with a single left bracket and actually don't really solve all issues for folders with a pair of brackets because even though "-file" allows the script to run, there will be further issues if there is a filename parameter passed to the script, but that's another issue. Let's see if we can just sort this single left bracket problem first.

Upvotes: 0

Views: 1610

Answers (2)

Paul T.
Paul T.

Reputation: 4907

Looks like that you can use the -InputFormat with the powershell command to help?
The brackets will need double backtick characters within the single quotes, the cat command only needed a single backtick like the cd command:

PS C:\> cat '.\Test`[\test.ps1'

echo "hello"
PS C:\> powershell -InputFormat "text" 'c:\test``[\test.ps1'
hello

Upvotes: 1

pxDav
pxDav

Reputation: 1814

Use ` before a bracket.

For example, I made a folder called hi[, now to go to that directory, use cd 'hi`[' and it will work.

Note: It only works with single quote ('), using double quotes (") throws an error

Upvotes: 1

Related Questions