0
votes

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:

  • C:\m\tag\testscript.ps1 'C:\m\tag\my'file.txt' <<<<
    • CategoryInfo : ParserError: (:String) [], ParentContainsErrorRecordException
    • FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
3
Be useful to know what the error is. If that quote is stripped out before the Get-Item is called then you would be getting FileNotFound type exception and that is not a fault of PowerShell but maybe the batch that is consuming the character. - Matt
Thnaks Matt: I get an error that says that the TerminatorExpectedAtEndOfString. I'm iserting more details on my question - user2033100

3 Answers

0
votes

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%\"
0
votes

How are you passing the parameter?

This works:

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

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