0

Is there a way to call a function when using an equation within Powershell.

I am trying to something like the following however the last line returns an error You must provide a value expression....

function quote($str) {
    return """" + $str  + """";
};
$a= "abc: " + quote('hi'); # <-- Doesn't Work

I realize I could assign the quote to an intermediate variable and then do the concatenation ($q=quote('hi'); $a="abc: " + q$) however I am hoping there is a simpler syntax.

webwake
  • 1,154
  • 1
  • 13
  • 26
  • 1
    Though it has been pointed out in a comment to @gms0ulman's answer, one point bears emphasizing: in PowerShell calling a function with parenthesis around the argument is usually _WRONG_. For certain technical reasons it will seem like it works on occasion, but unless you know what you are doing, it is much better to use `quote 'hi'` rather than `quote('hi')`. As I point out in [this SO answer](https://stackoverflow.com/a/15883080/115690) there are several wrong ways to call a function but only two right ways. – Michael Sorens May 28 '17 at 23:10

2 Answers2

2

Is this what you mean:

function quote($str) {
    return """" + $str  + """";
};
$a= "abc: " + $(quote('hi'));

# edit: as per Joey's comment, this will also work:
$a= "abc: " + (quote('hi'));

Edit

Re-written using PowerShell syntax:

# Function name is verb-noun, from approved verbs
# https://msdn.microsoft.com/en-us/library/ms714428(v=vs.85).aspx

Function Add-Quote{

    # parameters this function takes
    param([string]$str)

    # No need for return and semi colon. 
    # I tend to use return as it makes my code reading easier 
    """" + $str  + """"
}

$a = "abc: " + (Add-Quote -str 'hi')
G42
  • 9,791
  • 2
  • 19
  • 34
  • That's it. Exactly what I was looking for and so simple. – webwake May 26 '17 at 14:06
  • 1
    No need for a sub-expression here, simple parentheses suffice. – Joey May 26 '17 at 14:17
  • 1
    There's also no need to parenthesize the argument(s) to functions. This just breeds bad habits where passing multiple arguments to functions won't work as expected. – Joey May 26 '17 at 14:21
  • 1
    Agreed, but I'm leaving that as in OP's question as the whole function is clearly not PowerShell-native (the return, the semi-colons, not using param etc). – G42 May 26 '17 at 14:27
  • @gms0ulman thanks for the explanation and for the more powershell style version as well. – webwake May 26 '17 at 14:45
1

You could use the format operator -f to insert the string.

function quote {
    param($str)
    "`"$str`""
}
$a = 'abc: {0}' -f (quote 'hi')
BenH
  • 9,766
  • 1
  • 22
  • 35