我目前正在尝试编写一个显示域中每个组和用户的脚本。
Import-Module ActiveDirectory
$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)
$Table = @()
$Record = [ordered]@{ "Group Name" = ""; "Name" = ""; "Username" = ""; }
Foreach ($Group in $Groups) {
$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname
foreach ($Member in $Arrayofmembers) {
$Record.Set_Item("Group Name", $Group)
$Record.Set_Item("Name", $Member.name)
$Record.Set_Item("Username", $Member.samaccountname)
$objRecord = New-Object PSObject -property $Record $Table += $objrecord
}
}
$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation
它总是返回这些错误:
New-Object : A positional parameter cannot be found that accepts argument '+='.
At C:\Users\tech\Desktop\list.ps1:17 char:14
+ $objRecord = New-Object PSObject -property $Record $Table += $objrecord
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-Object], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
New-Object : A positional parameter cannot be found that accepts argument '+='.
At C:\Users\tech\Desktop\list.ps1:17 char:14
+ $objRecord = New-Object PSObject -property $Record $Table += $objrecord
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-Object], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
一遍又一遍重复。
任何帮助将不胜感激!
顺便说一下这是服务器 2012 R2
答案1
您的问题(如错误所述)是这一行:
$objRecord = New-Object PSObject -property $Record $Table += $objrecord
$Record
您需要在和之间添加新行$Table
:
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
但是,您可以简化并删除它。这是我对您的脚本的修改版本:
Import-Module ActiveDirectory
# Removed "Where" as it filtered nothing; no need for parens; no need to select name before expanding
$Groups = Get-AdGroup -filter * | select -expandproperty name
$Table = @()
foreach ($Group in $Groups) {
$arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname
foreach ($Member in $Arrayofmembers) {
# You can just declare an ordered object inline as a literal rather than pre-declaring.
$table += [ordered]@{
"Group Name" = $Group;
"Name" = $Member.name;
"Username" = $Member.samaccountname
}
}
}
$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation