powershell - 使用“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
解决方案
您似乎正在寻找,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
推荐阅读
- cypress - cypress run:保持测试运行器打开
- laravel - Laravel登录测试在phpunit中失败
- reactjs - React 演示与容器客户端验证
- android - Android Rxjava2 bindToLifecycle
- azure-devops - 在 VSTS 部署到 App Center 构建任务中格式化发行说明
- ios - Custom circular progress view in awakeFromNib
- apollo - Apollo GraphQL 客户端:如何区分对 watchQuery 的乐观响应和真实响应
- cordova - PhoneGap-push-plugin 和 request-location-accuracy 冲突
- javascript - 在 select 上调用 val() 有时会返回 null
- go - 如何将一系列 uint16 转换为 float32?