首页 > 解决方案 > 使用“2”参数调用“子字符串”的异常:“索引和长度必须引用字符串中的位置。参数名称:长度”

问题描述

如果可以请帮助解决以下错误。我在这些线上遇到了错误。它确实创建了帐户。它确实将名字的第一个字母转换为大写,对于姓氏也是如此。但是在它执行之后会抛出以下错误。它一直持续到我停止为止。

ForEach ($User in $Users) {
        $FirstName = $User.FirstName.Substring(0,1).toupper() + $User.FirstName.Substring(1).tolower()
        $LastName = $User.LastName.Substring(0,1).toupper() + $User.LastName.Substring(1).tolower()
        $SAM = $user.FirstName + $user.LastName.Substring(0,1)



Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string. Parameter name:  length" At C:\Users\student\Automate\CreateADaccount copy.ps1:17

char:5
+ $FirstName = $User.FirstName.Substring(0,1).toupper() + $User.d ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException   Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string. Parameter name: length" At C:\Users\student\Automate\CreateADaccount copy.ps1:18 char:5
+ $LastName = $User.LastName.Substring(0,1).toupper() + $User.d ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException

标签: powershell

解决方案


您似乎正在寻找,Title Case并且可以通过以下方式实现相同的目标,

$SAM = (Get-Culture).TextInfo.ToTitleCase($User.Firstname.ToLower()) + $User.Lastname.Substring(0,1).ToUpper()

或者,

$Firstname = (Get-Culture).TextInfo.ToTitleCase($User.Firstname.ToLower())
$Lastname = (Get-Culture).TextInfo.ToTitleCase($User.Lastname.ToLower())
$Lastname_Initials = $Lastname.Substring(0,1)
$SAM = $Firstname + $Lastname_Initials

推荐阅读