user2033100
user2033100

Reputation: 3

Powershell parameter $args[0] with quotes

I'm running a PowerShell script invoked from a batch that pass a filename as first parameter. Inside the script I use:

$file = Get-Item -LiteralPath $args[0]

But when the filenames contains a quote (I.E: my'file.txt) the get-item triggers an error. I've tried to remove the -LiteralPath parameter but the problem is the same. The syntax of the script is

$file = Get-Item -LiteralPath $args[0] write-host $file cmd /c pause

If I run the script against my'file.txt I get:

Upvotes: 0

Views: 1276

Answers (3)

CB.
CB.

Reputation: 60910

Supposing you are passing the path in this way in your file batch:

powershell.exe  C:\path\myscript.ps1 "%1%"

you need to escape the quote:

powershell.exe  C:\path\myscript.ps1 \"%1%\"

Upvotes: 0

Keith Hill
Keith Hill

Reputation: 201622

I think that maybe by the time PowerShell sees the filename cmd has stripped off any surround double quotes so PowerShell sees the lone single quote as a parse error. Try specifying the filename like so

my''file.txt

Upvotes: 0

mjolinor
mjolinor

Reputation: 68243

How are you passing the parameter?

This works:

.{gi -literalpath $args[0]} "my'file.txt"

Upvotes: 0

Related Questions