首页 > 解决方案 > cd 程序文件错误:找不到位置参数

问题描述

PS C:\> cd Program Files

当我发出这个命令时,我不知道为什么,但它不接受Program Files. 相同的命令在cmd.

这是它显示的错误:

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

标签: powershell

解决方案


正如Maximilian Burszley 的有用答案中所述,Program Files被解析为两个参数,因为空格用于分隔命令行参数。

您的使用尝试cd Program Files可能会受到cmd.exe(遗留命令提示符)的启发,这种语法确实有效;然而,即使在那里,它在概念上也违反了通常的参数解析规则。

因此,您需要使用一种引用形式才能将包含空格的值作为单个参数传递。

你有几个选项来实现这个引用:

  • 使用文字值,即应该按原样使用的值'...'

  • 在要嵌入"..." 变量引用(例如$HOME)或子表达式(例如$(Get-Date).

  • 用于`引用(转义)单个字符。

因此,您可以使用以下任何一种:

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

此外,您可以使用tab-completion将包含空格的路径的(无空格)前缀扩展为其完整形式,并隐式应用引用

例如,如果你在里面C:\并且你输入:

cd Program<tab>

PowerShell 自动完成以下命令:

 cd '.\Program Files\'

请注意Program Files(以及.\引用当前目录和尾随\以指示目录。)是如何自动单引号引起来的。


推荐阅读