Chase Florell
Chase Florell

Reputation: 47367

Auto-Escape dynamic strings in Powershell

I've got a string that will be dynamically generated from a 3rd party application

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

I need to be able to verify this path in a function.

$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

The problem is that it fails on the square brackets.

How can I automatically escape the square brackets in order to validate the file?

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

Upvotes: 3

Views: 1024

Answers (2)

Adil Hindistan
Adil Hindistan

Reputation: 6605

Can you try using "test-path -literalpath $path" ?

Upvotes: 0

Bill_Stewart
Bill_Stewart

Reputation: 24525

Use -LiteralPath instead of -Path; e.g.:

if ( test-path -literalpath $path ) {
  ....
}

Bill

Upvotes: 5

Related Questions