Powershell 脚本显示所有组及其用户

Powershell 脚本显示所有组及其用户

我目前正在尝试编写一个显示域中每个组和用户的脚本。

        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

Get-AdGroup -filter * |
    ForEach-Object{
        $groupname=$_.Name
        Get-ADGroupMember $_ |
            ForEach-Object{
                [pscustomobject]@{
                    GroupName=$groupname
                    Name=$_.name
                    SamAccountNamename=$_.samaccountname
                }
            }
    }

答案2

您需要将 $objRecord 初始化为一个数组:

$objRecord = @()

然后你可以 += 它。

另外,你应该这样做:

$objRecord += New-Object PSObject -property $Record $Table

代替:

$objRecord = New-Object PSObject -property $Record $Table += $objrecord

即:您正在执行 2 项作业。您要么执行 a=a+1,要么执行 a+=1。

不过,我会接受史蒂夫的回答。

相关内容