导入CSV以验证许多用户在多个组中,然后导出到Excel文件

时间:2016-03-11 20:30:30

标签: powershell

我一直在尝试编写一个脚本来验证组成员身份。

我有一个csv文件,其中包含以下内容:

ticket, User, Group
ticket 1, User A, Group A
ticket 2, User B, Group A
ticket 3, User C, Group B
ticket 4, User D, Group A
ticket 5, User E, Group B

我需要一个脚本来验证用户是否在组中,并且输出结果是否在csv文件中。

到目前为止,我所做的似乎做了我想做的事情:

Import-CSV $File | `
ForEach {
$users = $_.User;
$group = $_.Group;
$ticket = $_.Ticket

$members = Get-ADGroupMember -Identity "$group" -Recursive | Select -ExpandProperty SAMAccountName 
IF($members -contains $users) {Write-Host "$users in $group"} 
Else { Write-Host "$users not in $group"}
}
}

所以这就是“用户A在A组中”和“用户B不在A组”等等,这几乎就是我想要的。

现在如何让我的csv输出文件执行以下操作:

Ticket, User, Group, in group?
ticket 1, User A, Group A, true
ticket 2, User B, Group A, true
ticket 3, User C, Group B, false
ticket 4, User D, Group A, false
ticket 5, User E, Group B, true

True =用户在群组中 False =用户不在群组中

2 个答案:

答案 0 :(得分:0)

试试这个:

$csv = @"
ticket, User, Group
ticket 1, User A, Group A
ticket 2, User B, Group A
ticket 3, User C, Group B
ticket 4, User D, Group A
ticket 5, User E, Group B
"@ | ConvertFrom-Csv

$groups = $csv.group | select -Unique

$results = @(foreach ($group in $groups) {
    $members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SAMAccountName
    $csv | ? group -eq $group | select *, @{n='InGroup';e={$_.user -in $members}}
})

$results

答案 1 :(得分:0)

使用Add-Member将测试结果添加到新的NoteProperty中。例如:

Import-Csv -Path "c:\inputfile.csv" | ForEach-Object {

    $members = Get-ADGroupMember -Identity $_.Group -Recursive | Select -ExpandProperty SAMAccountName
    #in group?
    $ingroup = $members -contains $_.User
    #Add result to a new property and use -PassThru to output to pipeline
    $_ | Add-Member -MemberType NoteProperty -Name InGroup -Value $ingroup -PassThru

} | Export-Csv -Path "c:\outputfile.csv" -NoTypeInformation

示例输出:

"ticket","User","Group","InGroup"
"ticket 1","User A","Group A","False"
"ticket 2","User B","Group A","True"
"ticket 3","User C","Group B","False"
"ticket 4","User D","Group A","True"
"ticket 5","User E","Group B","False"