简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM