Powershell中的Auto-Escape动态字符串

Cha*_*ell 3 powershell escaping

我有一个字符串,它将从第三方应用程序动态生成

$somePath = "D:\some\path\name.of - my file [20_32_21].mp4"
Run Code Online (Sandbox Code Playgroud)

我需要能够在函数中验证此路径.

$somePath = "D:\some\path\name.of - my file [20_32_21].mp4"

Function ValidatePath{
    Param($path)
    if(Test-Path $path){
        Write-Host "Worked"
    } else {
        Write-Host "Didn't Work"
    }
}

ValidatePath $somePath 
# DIDN'T WORK
Run Code Online (Sandbox Code Playgroud)

问题是它在方括号上失败了.

如何自动转义方括号以验证文件?

# Path needs to look like this
$somePath = "D:\some\path\name.of - my file ``[20_32_21``].mp4"
ValidatePath $somePath 
# WORKED!!!
Run Code Online (Sandbox Code Playgroud)

Bil*_*art 5

使用-LiteralPath而不是-Path; 例如:

if ( test-path -literalpath $path ) {
  ....
}
Run Code Online (Sandbox Code Playgroud)

法案