我是 PowerShell 新手(来自 Bash),我无法理解为什么我构建的路径有时有效,而其他路径则无效:
> E:\Installers\wget\wget-win32-1.19.1.exe --version
GNU Wget 1.19.1 built on mingw32.
...OK
> $rootPath = E:\Installers
> echo ${rootPath}
E:\Installers
> dir ${rootPath}\wget\wget-win32-1.19.1.exe
Directory: E:\Installers\wget
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 19/04/2024 15:50 3481920 wget-win32-1.19.1.exe
> ${rootPath}\wget\wget-win32-1.19.1.exe --version
At line:1 char:12
+ ${rootPath}\wget\wget-win32-1.19.1.exe --version
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token '\wget\wget-win32-1.19.1.exe' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
为什么
${rootPath}
与 dir
一起使用而不是单独使用?
为什么
与${rootPath}
一起使用而不是单独使用?dir
这在 about Parsing 文档中的 Argument mode 中进行了解释。特别是要点:
- 除了仍然需要转义的元字符之外,其他所有内容都被视为可扩展字符串。请参阅处理特殊字符。
因此,本质上,传递给
dir
(Get-ChildItem
) 的参数被解释为就好像它是一个可扩展字符串 "${rootPath}\wget\wget-win32-1.19.1.exe"
:
$rootPath = 'E:\Installers'
& {param([string] $path) $path } ${rootPath}\wget\wget-win32-1.19.1.exe
# Parameter binding resolves the concatenation as:
# `E:\Installers\wget\wget-win32-1.19.1.exe`
但是,在您的第二次尝试中,PowerShell 无法确定您正在尝试执行的操作是通过将变量值
${rootPath}
与字符串的其余部分 \wget\wget-win32-1.19.1.exe
连接起来来创建新字符串,您需要通过包装来帮助它可扩展字符串中的表达式,然后使用点源运算符 .
或调用运算符 &
调用该路径,详细信息请参见 关于运算符:
& "${rootPath}\wget\wget-win32-1.19.1.exe" --version
其他替代方案可以使用
Join-Path
:
& (Join-Path ${rootPath} wget\wget-win32-1.19.1.exe) --version
或者,也许调用命令信息实例,PowerShell 会自动为您解析 winget 的路径:
& (Get-Command winget) --version