PowerShell: Converting first character of a string to uppercase


The below converts the first character of $givenname and $sn variables to uppercase. This is useful if you are receiving information from an external form and need to convert them to a useable format.
 


$givenname = Read-Host "First Name:" 


$sn = Read-Host "Last Name:" 




#Converts first letter of First/Lastname to uppercase


$givenname = $givenname.substring(0,1).toupper()+$givenname.substring(1).tolower()    


$sn = $sn.substring(0,1).toupper()+$sn.substring(1).tolower()

Next PostNewer Post Previous PostOlder Post Home

3 comments:

  1. thanks, dude. this was the finishing touch on this script i've been working on.

    ReplyDelete
  2. Better: $sn = $sn.Replace($sn[0],$sn[0].ToString().ToUpper())

    ReplyDelete
  3. That last one is not a good way to do it. If the first character appears elsewhere in the string then Replace() will uppercase it everywhere. Use the clumsy but precise substring().

    ReplyDelete