0

I am trying to figure out how to pass a paramter that contains special characters in Powershell to an Object inside my function. Here is an example of my code.

 function a{
 param(
 [string]$string    
 )
 #convert to URL encoding here
 #Query API
 #Return JSON values
 }

Now I type this in Powershell

 PS> a  foo(foo; bar) foo/bar ver1.0

And it fires on an error for ";" and then ")" being part of the string

Here is the error:

 At line:1 char:32
 + a  foo(foo; bar) foo/bar ver1.0
 +                                ~
 Missing closing ')' in expression.
 At line:1 char:41
 + a  foo(foo; bar) foo/bar ver1.0
 +                                         ~
 Unexpected token ')' in expression or statement.
 + CategoryInfo          : ParserError: (:) [],        ParentContainsErrorRecordException
 + FullyQualifiedErrorId : MissingEndParenthesisInExpression
3
  • 1
    Put the string you're passing in single quotes..? Commented Dec 16, 2016 at 15:18
  • @arco444 I'd prefer not to use single quotes each time that I do this. Is there any way around that? Commented Dec 16, 2016 at 15:25
  • You have to use quotes or escape special characters else PowerShell thinks they are separate and or special items. This is core of how PowerShell, and other languages parsing, works. Commented Dec 16, 2016 at 16:08

1 Answer 1

2

You have two options the way I see it.

Use single quotes:

a 'foo(foo; bar) foo/bar ver1.0'

Or escape all the special characters:

a foo`(foo`;` bar`)` foo/bar` ver1.0
Sign up to request clarification or add additional context in comments.

3 Comments

These are the only viable solutions it seems. So in this case I will accept this as the best answer. However, I reverted to using Read-Host to accept the input since it's easier than wrapping them in quotes each time.
@Badlarry Read-Host is returning a string for you and interpreting all input as that string. I suppose that works but seems odd that you think spending time typing on every execution is easier then just typing two quotes
@Matt hey Matt, I am only copying and pasting into the commandline. So I am actually not typing anything at all besides my cmdlet. I guess it's just my preference at this point. If I feel the need I can always change back to using the parameter method for a more modular approach. Thanks for the information as well in both of your posts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.