tl;dr
由于您的目录名称包含spaces, 你必须quote它,例如:
# 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 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Environment_Variables, in which case quoting is not required:[1]
cd $env:ProgramFiles
instead of cd 'C:\Program Files'
下面讨论如何传递字符串literals以空格作为单个参数。
如中所述Maximilian Burszley 的有用回答 https://stackoverflow.com/a/51459512/45375, Program Files
被解析为two参数,因为空格用于separate命令行参数。
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.
所以,你需要使用一种形式quoting为了传递一个值包含空格 as a single争论.
您有多种选择来实现此引用:
-
Use '...'
around值是literals,即应该使用verbatim; a '...'
字符串被称为verbatim(单引号)字符串 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Quoting_Rules#single-quoted-strings.
-
Use "..."
around您想要嵌入的值变量引用 (e.g., $HOME
) or 子表达式 (e.g., $(Get-Date)
;那是,"..."
弦乐演奏字符串插值,他们被称为可扩展的(双引号)字符串 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Quoting_Rules#double-quoted-strings.
-
Use `
引用(转义)asingle特点;`
, 所谓的backtick, 是PowerShell的通用转义字符 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Special_Characters.
因此,您可以使用以下任意一种:
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, 您可以使用制表符补全扩展(无空间)prefix包含空间的路径的完整形式隐式引用.
例如,如果您在C:\
然后你输入:
cd Program<tab>
PowerShell 自动完成命令:
cd '.\Program Files\'
请注意如何Program Files
(随着.\
引用当前目录。和一个尾随的\
指示目录。)是自动单引号.
Using 通配符表达式作为参数:
如前所述,在 PowerShell 中cd
是一个内置别名Set-Location https://learn.microsoft.com/powershell/module/microsoft.powershell.management/set-location cmdlet.
路过一条路位置上 - e.g. Set-Location 'C:\Program Files'
- 隐式地将其绑定到-Path
范围;就是这样,相当于Set-Location -Path 'C:\Program Files'
-Path
将其论证解释为通配符表达式 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Wildcards,这样你就可以做类似的事情Set-Location C:\Win*
为了改变为C:\Windows
(假设通配符表达式仅匹配one目录)。
棘手的是 - 与cmd.exe
- 这不仅仅是*
and ?
在 PowerShell 通配符表达式中具有特殊含义,但是[
and ]
以及(对于字符集和字符范围表达式,例如[abc]
and [a-c]
), 以便Set-Location Foo[1]
will not更改目录的工作字面上地 named Foo[1]
.
在这种情况下,您必须使用-LiteralPath
范围 -
Set-Location -LiteralPath Foo[1]
- 确保路径是解释的字面上地(逐字).
[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"