Powershell导出csv问题

时间:2018-01-12 14:59:45

标签: powershell csv active-directory

<# 
Run the Script On Active Directory to remove disabled users from All Groups and Set description what user was member of group if you have all the disable users in an OU. 
Just add -SearchBase "OU=disabled,DC=domain,DC=com" after  -filter 'enabled -eq $false' 

#> 
import-module activedirectory 
$users=get-aduser -filter 'enabled -eq $false' -SearchBase "OU=Lockdown,DC=home,DC=ac,DC=uk" -Properties samaccountname,memberof  |select samaccountname, @{n=’MemberOf’; e= { ( $_.memberof | % { (Get-ADObject $_).Name }) -join “,” }}  


#set description 
Foreach ($user in $users) 
{ Set-ADUser $user.samaccountname -Replace @{info="Was a member of :- $($user.memberof)"} 
# Export the list to csv
$Groups = (Get-ADPrincipalGroupMembership -Identity $user.SamAccountName | Select-Object -ExpandProperty name) -join ','

get-aduser $user.SamAccountName -properties memberof,samaccountname,givenname,surname | select samaccountname, @{name="Groups";expression={$Groups}} | export-csv "C:\Users\Administrator\Desktop\grpsss.csv" -Delimiter ";"



# Remove From all the Groups 
 Get-ADGroup -Filter {name -notlike "*domain users*"}  | Remove-ADGroupMember -Members $user.samaccountname -Confirm:$False  

} 


 $total = ($users).count  

 Write-Host "$total accounts have been processed..." -ForegroundColor Green 

此脚本从已禁用用户(从已禁用的OU)中删除所有组,它将这些组的名称添加到信息字段以及导出具有相同信息的csv。

Porblem是当禁用OU中有许多用户时,csv仅填充一个用户的groupmembership。问题是,我如何以csv格式导出所有用户及其组成员资格。所以我有一个已处理的所有用户的列表。

我一直认为export-csv会导出powershell进程的eveything吗?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您的脚本会尝试为每个用户导出csv:

Foreach ($user in $users) {
...
get-aduser $user.SamAccountName -properties memberof,samaccountname,givenname,surname | 
  select samaccountname, @{name="Groups";expression={$Groups}} |
  export-csv "C:\Users\Administrator\Desktop\grpsss.csv" -Delimiter ";"
...
}

但是,这意味着只有在此foreach块中运行的最后一个用户才会将其数据写入.csv文件。

这是因为Export-Csv默认会覆盖现有.csv文件的内容。因此,foreach块中的每个用户都会覆盖之前的用户。

要解决此问题,请将参数开关-Append添加到Export-Csv命令的末尾。 This will add on each users data to the end of the file rather than overwrite it例如

Foreach ($user in $users) {
...
get-aduser $user.SamAccountName -properties memberof,samaccountname,givenname,surname | 
  select samaccountname, @{name="Groups";expression={$Groups}} |
  export-csv "C:\Users\Administrator\Desktop\grpsss.csv" -Delimiter ";" -Append
...
}