简体   繁体   English

阵列的电源壳取回线

[英]power-shell retrieving line from array

So if I create an array from CSV file 因此,如果我从CSV文件创建数组

name,age,height,fruit
Jon,34,5,orange
Jane,23,4,apple
Dave,27,6,pear

I can read this in using 我可以阅读使用

$list = Import-CSV .....

but now i have the question. 但现在我有一个问题。 "tell me about Jane" “告诉我简”

So I could say 所以我可以说

foreach ($val in $list)
{
    if ($val.name = "jane" ) {$currentuser = $val}
}

write-host $currentuser.name
write-host $currentuser.age
write-host $currentuser.hight
write-host $currentuser.fruit

Is there a better way to do this rather than stepping through? 有没有比逐步执行更好的方法呢? In my actually case i have a list of staff from HR and a separate one from Active directory. 在我的实际情况中,我有一份来自HR的员工列表,另一份与Active Directory的员工列表。 I want to step through the HR list to find the user in AD, set this user as a variable/object. 我想逐步浏览HR列表以找到AD中的用户,将此用户设置为变量/对象。 and then update the user using information from HR. 然后使用来自HR的信息来更新用户。

The above method will work but seems very inefficient to be loping through two lists of several thousand users. 上面的方法可以工作,但要遍历几千个用户的两个列表似乎效率很低。

Given the array created from the CSV, I want a method that by inputting the string "jane" it will return jane's info to a object i can use. 给定从CSV创建的数组,我想要一个方法,通过输入字符串“ jane”,它将把jane的信息返回给我可以使用的对象。

If you have two lists, both with distinct keys by which the two can be correlated, the best way is to store one list in a lookup table (any type of dictionary will do, including a hashtable in PowerShell), and then loop sequentially through the other list: 如果您有两个列表,并且两个列表都有不同的键,可以通过这两个键进行关联,则最好的方法是将一个列表存储在查找表中(任何类型的词典都可以,包括PowerShell中的哈希表),然后依次循环浏览其他清单:

$HRList = @'
Name,Position,Department
John,Manager,Sales
Bob,Worker,Production
Sally,Accountant,Finance
'@ |ConvertFrom-Csv

$ADList = @'
Name,Username
Sally,sallysalt
Bob,bobburrows
John,johnjames
'@ |ConvertFrom-Csv

# Convert the AD list to a hash table
$ADLookupTable = @{}
foreach($ADUser in $ADList)
{
    $ADLookupTable[$ADUser.Name] = $ADUser
}

# Go through HR list
foreach($HRUser in $HRList)
{
    # Now you can find the relevant object in the other list
    $ADUser = $ADLookupTable[$HRUser.Name]
    Set-ADUser -Identity $ADUser.Username -Title $ADUser.Position -Department $ADUser.Department
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM