1

I am new to PowerShell, but not scripting.

Why does this script:

$usr = "john.doe"
$usrname = $usr -split ".", 0, "simplematch"
$fullname = upperInitial($usrname[0]) + upperInitial($usrname[1])
write-host "Hello $fullname"

function upperInitial($upperInitialString) {
  return $upperInitialString.substring(0, 1).toupper() + $upperInitialString.substring(1).tolower()
}

return me just 'Hello John' and not 'Hello John Doe'?

1
  • What was the issue you are facing Commented May 23, 2017 at 12:37

1 Answer 1

4

It's not treating the second call of the upperInitial function as a function, it's treating it as a paramter of the first call to the function I think.

Either of these work:

$fullname = "$(upperInitial($usrname[0])) $(upperInitial($usrname[1]))"
write-host "Hello $fullname"

The above uses the subexpression operator $() to execute the functions within a double quoted string.

$fullname = (upperInitial($usrname[0])) + ' ' + (upperInitial($usrname[1]))
write-host "Hello $fullname"

This one combines the result of the two functions as you had intended, although I also added a space character because otherwise it was JohnDoe.

Sign up to request clarification or add additional context in comments.

2 Comments

Correct :-) This is a classic "why doesn't my C#-like syntax work in PowerShell" issue
There's also issues using parentheses with function calls. The syntax for calling a function in PowerShell is FunctionName $Arg1 $Arg2, not FunctionName($Arg1,$Arg2). They work like a cmdlet, not like a C# function. For a single argument function you probably won't have issues, but functions with multiple arguments will not work because parentheses have a different meaning in PowerShell. It's best to avoid looking like the C# syntax completely.

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.