0

I am creating a script that will allow batch creation of new users but am running into an issue with the creation of the array.

$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()

If I run this I get the error:

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
Todd Welch
  • 1,776
  • 2
  • 17
  • 23
  • Let us know if the accepted answer to the linked question doesn't solve your problem. – mklement0 Oct 07 '19 at 21:17
  • 1
    Or something like this: `$names = 1..2 | foreach { [pscustomobject]@{fname = read-host first; lname = read-host last } }` – js2010 Oct 07 '19 at 23:20

1 Answers1

0

You are creating an array with an fixed size of zero. As $fname[0] doesn't exist in the array you can't change it's value. One solution would be to use += to add an element to your existing array:

$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()

As a side note, I personally wouldn't use different arrays for my user information but instead create 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
Olaf Reitz
  • 684
  • 3
  • 10