【问题标题】:How To Create An Array Reading from Host? [duplicate]如何创建从主机读取的数组? [复制]
【发布时间】:2019-10-07 20:33:50
【问题描述】:

我正在创建一个允许批量创建新用户的脚本,但在创建数组时遇到了问题。

$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

【问题讨论】:

  • 如果接受的链接问题的答案不能解决您的问题,请告诉我们。
  • 或者类似这样的:$names = 1..2 | foreach { [pscustomobject]@{fname = read-host first; lname = read-host last } }

标签: powershell


【解决方案1】:

您正在创建一个固定大小为零的数组。由于数组中不存在 $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

【讨论】:

    猜你喜欢
    • 2012-03-18
    • 2016-03-25
    • 2015-03-18
    • 2021-03-26
    • 1970-01-01
    • 2019-02-19
    • 2012-01-14
    • 2019-01-01
    • 2019-02-23
    相关资源
    最近更新 更多