PowerShell: "No positional parameter found" - powershell

File.csv contains a list of groups that are in different domains. I'm trying to recursively pull the list of users in the list but it keeps giving me the following at at $adgroup:"No positional parameter found"
$groups = Get-Content -path 'C:\Temp\file.csv'
$result = foreach ($group in $groups)
{​​​​​​​
foreach ($domain in $domains)
{​​​​​​​
$adGroup = Get-ADGroup $group -Searchbase "" -server thegc:3268
$x = ($x.DistinguishedName -split ',DC=')[1]
$members = (Get-ADGroupMember $adGroup -Server $x -recursive).where({​​​​​​​
$_.ObjectClass -eq 'User'
}​​​​​​​)
foreach($user in $members)
{​​​​​​​
[pscustomobject]#{​​​​​​​
GroupName = $adGroup.Name
samAccountName = $user.samAccountName
distinguishedName = $user.distinguishedName
name = $user.name
}​​​​​​​
}​​​​​​​
}​​​​​​​
}​​​​​​
$result | Export-Csv c:\temp\output.csv -NoTypeInformation
Any help would be appreciated here-

Related

Exporting a list of AD Users and their group through powershell

I'm looking to export users with their groups in Active Directory through powershell, but I can't seem to get the pipe to work for some reason the powershell script I'm using right now is
`
$groups = get-adgroup -filter *
foreach ($group in $groups) {
$naam = $group.name
$members = Get-ADGroupMember -identity $group
write-host “Group: $naam”
write-host “————————————-”
foreach ($member in $members) {
$memnaam = $member.samaccountname
write-host “$naammem”
}`
I just can't seem to figure this out any recommendations?
`
$groups = get-adgroup -filter *
foreach ($group in $groups) {
$naam = $group.name
$members = Get-ADGroupMember -identity $group
write-host “Group: $naam”
write-host “————————————-”
foreach ($member in $members) {
$memnaam = $member.samaccountname
write-host “$naammem”
} | Export-CSV c:\FileName.csv`
Check for typos in variable names (you have one) and that you've closed all parentheses and braces. Even better, don't use variables where not needed:
$groups = get-adgroup -Filter *
# If you save your search as an object you won't need to re-run it multiple times to use the data
Write-Host "Processing groups"
$SearchResult = $Groups | ForEach-Object {
$GroupName = $_.Name
# Some simple error trapping
Try {
# Writing to host for informational only
Write-Host "$GroupName..." -NoNewline
$Members = (Get-ADGroupMember -Identity $_ -ErrorAction Stop).SamAccountName
}
Catch {
$Members = $_
}
# Output results as an object
[pscustomobject]#{
Group = $GroupName
Members = $Members
}
Write-Host "Done"
}
Write-Host "Processing complete"
# If you want to display it in console
$SearchResult | Format-List
# Or a GridView
$SearchResult | Out-GridView

PowerShell: 'MemberOf' outputs a blank column instead of the 'Group Name' of the users

The below PowerShell script iterates through the groups listed in the test.csv file.
It pulls samAccountName and distinguishedName from each user in the various groups. However, when I try to pull groupName the output is "Microsoft.ActiveDirectory.Management.ADPropertyValueCollection". Not sure how to fix this-
$groups = Get-Content test.csv
$domains = (Get-ADForest).Domains
foreach ($group in $groups)
{
foreach ($domain in $domains)
{
if (Get-ADGroup $group -Server $domain)
{
Get-ADGroupMember $group -Server $domain | select groupName, samAccountName, distinguishedName | Export-Csv c:\temp\file.csv -notypeinformation -append
}
}
}
I have tried the below, but it just outputs an empty column instead:
$groups = Get-Content test.csv
$domains = (Get-ADForest).Domains
foreach ($group in $groups)
{
foreach ($domain in $domains)
{
if (Get-ADGroup $group -Server $domain)
{
Get-ADGroupMember $group -Server $domain | select samAccountName, distinguishedName |
Get-ADUser #{name = ‘MemberOf’;’expression={$_.MemberOf -join “;”}} |
Export-Csv c:\temp\file.csv -notypeinformation
}
}
}
Try this, I added some optimization to your code :)
Note, try {...} catch {...} is more or less needed here because both cmdlets Get-ADGroup and Get-ADGroupMember will throw if the object is not found.
$ErrorActionPreference = 'Stop'
$groups = Get-Content test.csv
$domains = (Get-ADForest).Domains
$result = foreach ($group in $groups)
{
foreach ($domain in $domains)
{
try
{
$adGroup = Get-ADGroup $group -Server $domain
$members = (Get-ADGroupMember $adGroup -Server $domain).where({
# Here, I assume your looking only for user objects
# since you're next cmdlet is Get-ADUser
$_.ObjectClass -eq 'user'
})
foreach($user in $members)
{
# !!! $adUser = Get-ADUser $user >> This is not needed,
# Get-ADGroupMember already brings you the samAccountName of
# each object
# Here you can cast the result, I assume
# you want your CSV to have the Name of the Group and
# the samAccountName and distinguishedName of each user
[pscustomobject]#{
GroupName = $adGroup.Name
samAccountName = $user.samAccountName
distinguishedName = $user.distinguishedName
}
}
}
catch
{
Write-Warning $_
}
}
}
$result | Export-Csv c:\temp\file.csv -NoTypeInformation
If you change your select statement to:
select-object #{n='groupName';expression={$group}}, samAccountName, distinguishedName
It should output the $group input of Get-ADGroupMember for that column.

What is method to use foreach on a txt file?

Below embedded foreach commands needs $user to come from list.txt, dump groups from AD into $user.txt file and remove.
How do I specify $user as each line in the list.txt whild also verifying the formatting of the list inside the list.txt is just one name per line, no comma?
foreach ($user in .\list.txt) {
$groups = (Get-ADUser $user -Properties MemberOf).MemberOf
Add-Content -Path C:\TEMP\RemoveGroups\$user.txt -Value $groups
foreach ($group in $groups) {
Remove-ADGroupMember $group -Member $user
}
$List = Get-Content .\List.txt
Foreach ($User in $List){
$Groups = (Get-ADUser $user -Properties MemberOf).MemberOf
Foreach ($GroupDN in $Groups){
Try {
$Group = Get-ADGroup $GroupDN
Remove-ADGroupMember $Group -member $user -ErrorAction Stop
$Succeed = $Succeed,$Group.Name -join ";"
}
Catch {
$Failed = $Failed,$Group.Name -Join ";"
}
}
$temp = New-Object psobject -ArgumentList #{
User = $User
Succeed = $Succeed
Failed = $Failed
}
Export-Csv -InputObject $temp -Path C:\TEMP\RemoveGroups\Result.csv -Encoding UTF8 -NoTypeInformation -Append
}
You will get the CSV file like this:
User,Succeed,Failed
user1,Group1;Group2,Group3;Group4
user2,Group2;Group3,Group1;Group4
You can use the following code.
# Read the list of users to an array of strings.
$users = Get-Content .\list.txt
foreach ($user in $users) {
# Validate that the username only contains a-z and 0-9.
if ($user -match "^[a-zA-Z0-9]+$") {
$groups = (Get-ADUser $user -Properties MemberOf).MemberOf
Add-Content -Path C:\TEMP\RemoveGroups\$user.txt -Value $groups
foreach ($group in $groups) {
Remove-ADGroupMember $group -member $user
}
}
}

Script to get Group Member, group starting with "ADM*"

I have a requirement to generate a CSV report to get group members. However, I there are many child domains which contains groups starting with ADM.
I need report in the following format:
GroupName User Company LasLogon CN
ADM_AM UserOne CP1
I've found one script on internet:
Get-ADGroup -Server dc1.chd1.pd.local -Filter 'Name -like "ADM*"' |
ForEach-Object{
$hash=#{GroupName=$_.Name;Member=''}
$_ | Get-ADGroupMember -ea 0 -recurs |
ForEach-Object{
$hash.Member=$_.Name
New-Object psObject -Property $hash
}
} |
sort groupname,member
This script only gives me GroupName and UserName but not other information.
How can I generate this report?
I'm not sure what "ADM_AM, UserOne, CP1" is, but i got this much for you. I'm still new to powershell so forgive me if this is a lot of code =)
$array = #()
Foreach ($group in (Get-ADGroup -Server dc1.chd1.pd.local -Filter 'Name -like "ADM*"'))
{
$hash=#{Username ='';GroupName=$group.Name;Company='';LastLogon='';CN=''}
$members = $hash.GroupName | Get-ADGroupMember -Recursive -ErrorAction SilentlyContinue
Foreach($member in $members)
{
$properties = $member.SamAccountName | Get-ADUser -Properties SamAccountName, Company, lastLogon, CN
$hash.Username = $properties.SamAccountName
$hash.Company = $properties.Company
$hash.LastLogon = $properties.lastLogon
$hash.CN = $properties.CN
$obj = New-Object psObject -Property $hash
$array += $obj
}
}
$array | Export-Csv C:\ -NoTypeInformation
Here is what I would do, Im sure you can shorten it. You shoud specify a searchbase. Once you have the members samaccountname, you can use Get-ADUser to get whatever fields you want.
$GrpArr = #()
$Groups = get-adgroup -filter {name -like "adm*"} -searchbase "ou=Groups,dc=all,dc=ca" | select samaccountname
foreach ($group in $groups)
{
$GrpArr += $group
$members = get-adgroupmember $group | select samaccountName
foreach ($member in $members)
{
$memprops = get-aduser $member -properties company
$comp = $memprops.company
$grpArr += "$member,$comp"
}
}
$grpArr | export-csv c:\temp\Groups.csv -NoTypeInformation

PowerShell script to return members of multiple security groups

I need to return all members of multiple security groups using PowerShell. Handily, all of the groups start with the same letters.
I can return a list of all the relevant security groups using the following code:
Get-ADGroup -filter 'Name -like"ABC*"' | Select-Object Name
And I know I can return the membership list of a specific security group using the following code:
Get-ADGroupMember "Security Group Name" -recursive | Select-Object Name
However, I can't seem to put them together, although I think what I'm after should look something like this (please feel free to correct me, that's why I'm here!):
$Groups = Get-ADGroup -filter 'Name -like"ABC*"' | Select-Object Name
ForEach ($Group in $Groups) {Get-ADGroupMember -$Group -recursive | Select-Object Name
Any ideas on how to properly structure that would be appreciated!
Thanks,
Chris
This is cleaner and will put in a csv.
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."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation
If you don't care what groups the users were in, and just want a big ol' list of users - this does the job:
$Groups = Get-ADGroup -Filter {Name -like "AB*"}
$rtn = #(); ForEach ($Group in $Groups) {
$rtn += (Get-ADGroupMember -Identity "$($Group.Name)" -Recursive)
}
Then the results:
$rtn | ft -autosize
Get-ADGroupMember "Group1" -recursive | Select-Object Name | Export-Csv c:\path\Groups.csv
I got this to work for me... I would assume that you could put "Group1, Group2, etc." or try a wildcard.
I did pre-load AD into PowerShell before hand:
Get-Module -ListAvailable | Import-Module
This will give you a list of a single group, and the members of each group.
param
(
[Parameter(Mandatory=$true,position=0)]
[String]$GroupName
)
import-module activedirectory
# optional, add a wild card..
# $groups = $groups + "*"
$Groups = Get-ADGroup -filter {Name -like $GroupName} | Select-Object Name
ForEach ($Group in $Groups)
{write-host " "
write-host "$($group.name)"
write-host "----------------------------"
Get-ADGroupMember -identity $($groupname) -recursive | Select-Object samaccountname
}
write-host "Export Complete"
If you want the friendly name, or other details, add them to the end of the select-object query.