Home > Software engineering >  Powershell - How to pass arguments with apostrophes in them?
Powershell - How to pass arguments with apostrophes in them?

Time:11-11

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

CodePudding user response:

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:'=''%'"

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 enter image description here

  • Related