如何将多个用户或值添加到数组中

如何将多个用户或值添加到数组中

我想创建一个 powershell 脚本,其中我想将多个值添加到数组(添加到数组中)。

例如:我公司有 10 个用户,我想创建他们的 AD 帐户(不使用 csv 文件),如果我使用“Read-Host”,如下所示。我可以循环“read-host”显示 10 次并将值添加到数组和列表中,如下所示吗?

$FirstName = Read-Host "Enter the first name of the employee"
$LastName = Read-Host "Enter the last name of the employee"
[INT]$empid = Read-Host "Enter the employee number"
$group = Read-Host "Enter the group name"
$homedrive = Read-Host "Enter the home drive"

$NewHire = @{}
$NewHire.Name = $FirstName
$NewHire.Empid = $empid
$NewHire.LastName = $LastName
$NewHire.homedrive = $homedrive

$Objectname = New-Object PSobject -Property $NewHire

$objectname

该文件的输出如下,

名字 姓氏 Empid homedrive
---- -------- ----- ---------
phani ukkalam 3333 FDS      

答案1

您可以添加一个 wscript shell 来提示用户是否继续,并将其放入 do while 循环中。

这里的循环条件取决于用户按“是”来添加更多用户:

$wsh = new-object -comobject wscript.shell

do {
    $FirstName = Read-Host "Employee name"

    #and so on, and so on, end with this:

    $answer = $wsh.popup("Do you want to add more users?", 0,"More users?",4) 
    If ($answer -eq 6) { 
            $continue = $True 
        } else { 
            $continue = $False 
        } 
} while ($continue -eq $True) 

答案2

是的。这是一个例子。

$userCount = 10
$users = @()

1..$userCount | ForEach-Object {
    $FirstName = Read-Host "Enter the first name of the employee"
    $LastName = Read-Host "Enter the last name of the employee"
    [INT]$empid = Read-Host "Enter the employee number"
    $group = Read-Host "Enter the group name"
    $homedrive = Read-Host "Enter the home drive"

    $NewHire = @{}
    $NewHire.Name = $FirstName
    $NewHire.Empid = $empid
    $NewHire.LastName = $LastName
    $NewHire.homedrive = $homedrive

    $Objectname = New-Object PSobject -Property $NewHire

    $users += $Objectname
}

$users

答案3

尝试下面文章中的 Read-HostArray 函数,它提供了更好的解决方案,可以将数组值直接粘贴到文本框中并将其传递给脚本。

http://powershelldude.blogspot.com/2015/08/read-hostarray-function-to-paste-multi.html

答案4

这使用“Read-Host”cmdlet。通过此示例,您可以在代码前面添加选择用户数,而不是对其进行硬编码。

# This section asks for the number of users.  The string can be whatever you want.
$u = Read-Host -Prompt 'number of users'

# This section reads the string for the value that you entered previously
$userCount = $u

相关内容