mikexmagic
mikexmagic

Reputation: 73

strange script issue in Powershell

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'?

Upvotes: 1

Views: 40

Answers (1)

Mark Wragg
Mark Wragg

Reputation: 23405

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.

Upvotes: 4

Related Questions