Powershell 如何创建从主机读取的数组?
我正在创建一个允许批量创建新用户的脚本,但在创建数组时遇到了问题Powershell 如何创建从主机读取的数组?,powershell,Powershell,我正在创建一个允许批量创建新用户的脚本,但在创建数组时遇到了问题 $fname = @() $lname = @() $i = 0 $fname[$i] = Read-Host "`nWhat is the first name of the new user?" $fname[$i] = $fname[$i].trim() $lname[$i] = Read-Host "What is the last name of the new user?" $lname[$i] = $lname[
$fname = @()
$lname = @()
$i = 0
$fname[$i] = Read-Host "`nWhat is the first name of the new user?"
$fname[$i] = $fname[$i].trim()
$lname[$i] = Read-Host "What is the last name of the new user?"
$lname[$i] = $lname[$i].trim()
如果运行此命令,则会出现以下错误:
Index was outside the bounds of the array.
At line:1 char:1
+ $fname[$i] = Read-Host "`nWhat is the first name of the new user?"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], IndexOutOfRangeException
+ FullyQualifiedErrorId : System.IndexOutOfRangeException
Method invocation failed because [System.Object[]] does not contain a method named 'trim'.
At line:2 char:13
+ $fname[$i] = $fname.trim()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
您正在创建一个固定大小为零的数组。由于数组中不存在$fname[0],因此无法更改其值。一种解决方案是使用+=将元素添加到现有数组中:
$fname = @()
$lname = @()
$i = 0
$fname += Read-Host "`nWhat is the first name of the new user?"
$fname[$i] = $fname[$i].trim()
$lname += Read-Host "What is the last name of the new user?"
$lname[$i] = $lname[$i].trim()
作为补充说明,我个人不会对我的用户信息使用不同的数组,而是创建PSCustomObject:
$UserTable = @()
$obj = New-Object psobject
$obj | Add-Member -MemberType NoteProperty -Name FirstName -Value (Read-Host "`nWhat is the first name of the new user?").Trim()
$obj | Add-Member -MemberType NoteProperty -Name LastName -Value (Read-Host "What is the last name of the new user?").Trim()
$UserTable += $obj
$i = 0
$UserTable[$i].FirstName
$UserTable[$i].LastName
如果链接问题的已接受答案不能解决您的问题,请告知我们:
$names=1..2 | foreach{[pscustomobject]@{fname=read host first;lname=read host last}