cd Program Files error: positional parameter cannot be found
Asked Answered
P

8

12
PS C:\> cd Program Files

When I give this command, I don't know why, but it is not accepting Program Files. The same command is working perfectly fine in cmd.

This is the error it shows:

Set-Location : A positional parameter cannot be found that accepts argument 'Files'.
At line:1 char:1
+ cd Program Files
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-Location], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
Polydactyl answered 21/7, 2018 at 19:12 Comment(4)
cd 'Program Files'Mcardle
After having typed the first chars hit [tab] (repeatedly) to cycle through names starting with those chars. Quotes and `.` prefix are added automatically as required.Recollected
@Olaf Sometimes, you're running into a stack of problems that aren't very related. Their profile states they're a student and their question shows lack of knowledge of powershell in general. I feel my answer explains the different elements well, but there are 2-3 different issues within this question.Demirelief
@TheIncorrigible1 I'm used to think that especially the younglings today even more than anything else using google as their first place to ask questions. But I might be wrong with this opinion. ;-) But I'm pretty sure about that they don't try to figure things out by themselfs. At least that's what I'm used to experiencing with our apprentices. Thanks for your answer anyway. Have a nice Sunday.Pasturage
W
29

tl;dr

Since your directory name contains spaces, you must quote it, e.g.:

# Note: In PowerShell, 'cd' is an alias of 'Set-Location'
cd 'Program Files'

Alternatively, if the intent is to change to the well-known programs folder (typically,
C:\Program Files), you may reference the relevant environment variable, in which case quoting is not required:[1]
cd $env:ProgramFiles instead of cd 'C:\Program Files'

The following discusses how to pass string literals with spaces as single arguments.


As stated in Maximilian Burszley's helpful answer, Program Files is parsed as two arguments, because spaces are used to separate command-line arguments.

Your attempt to use cd Program Files may be inspired by cmd.exe (the legacy Command Prompt), where this syntax indeed works; however, even there it conceptually violates the usual rules of argument parsing.

Therefore, you need to use a form of quoting in order to pass a value that contains spaces as a single argument.

You have several options to implement this quoting:

  • Use '...' around values that are literals, i.e., that should be used verbatim; a '...' string is called a verbatim (single-quoted) string.

  • Use "..." around values in which you want to embed variable references (e.g., $HOME) or subexpressions (e.g., $(Get-Date); that is, "..." strings perform string interpolation, and they're called expandable (double-quoted) strings.

  • Use ` to quote (escape) a single character; `, the so-called backtick, is PowerShell's general escape character.

Therefore, you could use any of the following:

cd 'Program Files'
cd "Program Files"  # as there are no $-prefixed tokens, same as 'Program Files'
cd Program` Files   # `-escape just the space char.

Also, you can use tab-completion to expand the (space-less) prefix of a space-containing path to its full form with quoting applied implicitly.

E.g., if you're in C:\ and you type:

cd Program<tab>

PowerShell automatically completes the command to:

 cd '.\Program Files\'

Note how the Program Files (along with .\ to refer to the current dir. and a trailing \ to indicate a dir.) was automatically single-quoted.


Using wildcard expressions as arguments:

As noted, in PowerShell cd is a built-in alias of the Set-Location cmdlet.

Passing a path positionally - e.g. Set-Location 'C:\Program Files' - implicitly binds it to the -Path parameter; that is it, is equivalent to Set-Location -Path 'C:\Program Files'

-Path interprets its argument as a wildcard expression, so that you can do something like Set-Location C:\Win* in order to change to C:\Windows (assuming that the wildcard expression matches only one directory).

The tricky thing is that - unlike in cmd.exe - it isn't just * and ? that have special meaning in PowerShell wildcard expressions, but [ and ] as well (for character-set and character-range expressions such as [abc] and [a-c]), so that Set-Location Foo[1] will not work for changing to a directory literally named Foo[1].

In that case, you must use the -LiteralPath parameter -
Set-Location -LiteralPath Foo[1] - to ensure that the path is interpreted literally (verbatim).


[1] This even applies if you append a space-less literal, e.g. cd $env:ProgramFiles\Git; however, if the literal part contains spaces, quoting is again needed; while, e.g., cd $env:ProgramFiles\'Common Files' works, the preferable approach is to enclose the entire argument in "...": cd "$env:ProgramFiles\Common Files"

Weinberger answered 21/7, 2018 at 22:55 Comment(0)
A
7
cd C:\Program` Files\ 

` just escape the space in folder name.

Atlanta answered 4/12, 2019 at 6:55 Comment(0)
D
4

The reason is invalid syntax. Each argument to a powershell command is separated by space, so what you're actually doing is something similar to:

Set-Location -Path Program -Arg2 Files

But Set-Location (aliased: cd) does not have any positional arguments for a second position, so it can't bind it to any parameters and use it in the command, hence the terminating error.


If you want a simpler cd alias, you could do something like this (in your $profile):

function ChangeDirectory {
    param(
        [Parameter(
            Position = 0,
            Mandatory,
            ValueFromRemainingArguments
        )]
        [string[]] $Path
    )

    Set-Location -Path ($Path -join ' ')
}
Set-Alias -Name cd -Value ChangeDirectory

Do note, however, that if you're not specifying a relative path (.\), it will use the root path of your current drive (most likely, C:\). This can be tuned in the function to test for both locations (relative and drive-rooted), but logic for figuring out which one to use if they both exist would be tricky (or can always default to relative).

Demirelief answered 21/7, 2018 at 19:41 Comment(3)
+1 for the explanation, but I wish you hadn't included the ValueFromRemainingArguments solution, because using arguments this way encourages "fuzzy thinking" - see github.com/PowerShell/PowerShell/issues/7190Weinberger
@Weinberger I understand that from a technical sense for consistency, but what I suggested is a profile modification to get the functionality desired. You shouldn't be setting locations in a script anyways. I'd argue Write-Host follows this "fuzzy thinking"Demirelief
It's not about cd / Set-Location in particular, it's about not indulging someone's lack of understanding of command-mode syntax with tricky workarounds that won't work in most other contexts - using ValueFromRemainingArguments this way is an ill-advised repurposing. Write-Host is rarely the right tool to begin with; that it can be thought of as obscuring how its arguments are parsed doesn't help; a quick experiment such as Write-Host 'a b'       c             d is enough to demonstrate that it too uses regular argument parsing.Weinberger
B
3

Use quotes (double or single) to go to the folder or path contains white spaces or special symbols.

Forexample:-

cd "C:\Users\LAPTOP0534\OneDrive - My Content (Active Directory)"

OR

cd 'OneDrive - My Content (Active Directory)\My Folder'

For your case it will be PS C:\> cd "Program Files"

Bloodred answered 18/6, 2022 at 11:39 Comment(0)
B
0

Just run your command prompt as administrator . See the picture attached. It will run easily

enter image description here

Berenice answered 16/12, 2022 at 22:0 Comment(1)
The premise of the question is that everything works as expected in cmd.exe, but not in PowerShell. Thus, there is no need to address cmd.exe's behavior, and suggesting that running as an administrator is necessary is ill-advised.Weinberger
P
0

Solving space in path issue with string literal " "

Petepetechia answered 12/2 at 3:46 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Forfar
E
-1

This is because of the space between the sentences. Enter code here You complete the tab. Replace PS F: > cd new folder with PS F: > cd "new folder" in the PowerShell. Or look at F: > cd './new folder'. I'm a beginner and you should try this.

Electrodialysis answered 11/6, 2022 at 15:53 Comment(0)
T
-1

You can also launch powershell from explorer writing pwsh over the path and click enter, that open powrshell in speific location, easier.

Trifid answered 8/9, 2023 at 4:40 Comment(1)
How does that solve the described problem?Dialogue

© 2022 - 2024 — McMap. All rights reserved.