powershell如何识别包含空格和括号的路径[重复]

问题描述 投票:0回答:1

我有以下问题。我有一个 ps1 脚本,它采用路径作为参数,然后检查该路径是否存在。如果路径没有空格和/或括号,例如“G:\Program Files\Utilities\SendTo2024 estPath1”,则代码给出所需的结果。

但是,如果代码中有括号和/或空格,例如 “G:\Programs\Utilities\SendTo2024 estPath1 est文件夹[9]t 0p”路径无法识别,并且没有给出预期结果。

这是我的 Powershell 脚本:

# Script name: Check-PathExistence.ps1

param (
[string]$Path
)

write-host $Path

if (-Not (Test-Path $Path)) {
    Write-Host "The path '$Path' does not exist."
} else {
    Write-Host "The path '$Path' exists."
}

我尝试了两条路。重要的是这两个路径都正确编写并且存在。 shell 中的输入由脚本所在工作目录中的终端执行。输入/输出看起来像这样:

输入1:

PS G:\\Programme\\Hilfsprogramme\\SendTo2024\\testPath1\> .\\check_if_path_exists.ps1 -path "G:\\Programme\\Hilfsprogramme\\SendTo2024\\testPath1\\ordner1"

输出1:

G:\\Programme\\Hilfsprogramme\\SendTo2024\\testPath1\\ordner1
The path 'G:\\Programme\\Hilfsprogramme\\SendTo2024\\testPath1\\ordner1' exists.

输入2:

PS G:\\Programme\\Hilfsprogramme\\SendTo2024\\testPath1\> .\\check_if_path_exists.ps1 -path "G:\\Programme\\Hilfsprogramme\\SendTo2024\\testPath1\\test ordner\[9\]t 0p"

输出2:

G:\\Programme\\Hilfsprogramme\\SendTo2024\\testPath1\\test ordner\[9\]t 0p
The path 'G:\\Programme\\Hilfsprogramme\\SendTo2024\\testPath1\\test ordner\[9\]t 0p' does not exist.
PS G:\\Programme\\Hilfsprogramme\\SendTo2024\\testPath1\>

我将机器人路径排除为“路径..存在”。那么 powershell 中是否有任何函数或其他可能性可以识别带有括号和/或空格的路径?

powershell path
1个回答
0
投票

PowerShell 中的大多数提供程序 cmdlet 都有 2 个路径参数 -

-Path
-LiteralPath

-Path
通常是默认值,并假设提供的路径是有效的glob模式 - 这意味着PowerShell将请求底层提供程序尝试和扩展通配符并解析匹配路径。

由于 PowerShell 将

[9]
视为单字符通配符描述符,因此
[
]
实际上从未被识别为路径本身的一部分。

要禁用路径中的通配符扩展,只需使用

-LiteralPath
参数即可:

Test-Path -LiteralPath $Path
© www.soinside.com 2019 - 2024. All rights reserved.