Powershell - How to pass arguments with apostrophes in them?

Viewed 305

I'm using a third party tool to do some AD manipulation. I run a powershell script and pass arguments to it.

Everything works except if that argument contains an apostrophe in it like Jerry O'Connor. I've tried lots of different escape combinations without any luck.

Here is my command: script.ps1 -name "'%name%'" and name contain is Jerry O'Connor.

The error is

Result:The string is missing the terminator: '.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

I've tried:

  • script.ps1 -name "'%name%'"
  • script.ps1 -name \"%name%\"
  • script.ps1 -name ''name''

all with same error.

If you run this at the PS CMD level you'll see the error

powershell echo -name "'Jerry O'Connor'"

Anyone know how to pass an argument to script.ps1 -name "name" where that argument contains an apostrophe?

Cheers

2 Answers

You need to escape any ' chars. inside the value of %name% as '' to make them work inside a single-quoted PowerShell string, which from cmd.exe you can do with %name:'=''%:

From cmd.exe / a batch file:

powershell.exe -Command ./script.ps1 -name "'%name:'=''%'"

If %name% contains verbatim Jerry O'Connor, the above expands to the following, which should work as intended:
powershell.exe -Command ./script.ps1 -name "'Jerry O''Connor'"


However, you can simplify quoting if you use the -File CLI parameter instead of -Command:

powershell.exe -File ./script.ps1 -name "%name%"

See also:

  • For guidance on when to use -Command vs. -File, see this answer

  • For a comprehensive overview of the PowerShell CLI, see this answer

Try the escape character as shown here:

$Test = "`'test`'"
$Test

enter image description here

Related