Getting user name through AD using powershell - powershell

I've been banging my head against this for a while and can't figure out why this isn't working.
Import-Module ActiveDirectory
$Users = Get-ADGroupMember -identity “Accounting” -recursive | select name | export-csv -path "D:\group.csv"
$csv = Import-Csv "D:\group.csv"
foreach ($user in $csv) {Get-ADUser -filter "'Name -eq ""$user""'"}

You have a couple of issues here I think.
You export the data just to import it again. Do you even need a second copy of the data?
Import-Csv will return an object array not just the names. There is more than one way to address this but this should be more what you are looking for
Import-Module ActiveDirectory
$Users = Get-ADGroupMember -identity “Accounting” -recursive | select name
foreach ($user in $Users) {Get-ADUser -filter {Name -eq $user.Name}}
Even that is more than it needs to be. Its redundant since Get-ADGroupMember already returns similar objects you need. What do you need to do with this data? If you really need Get-AdUser then just pipe the output to it.
Get-ADGroupMember -identity “Accounting” -recursive | Get-Aduser

$user is a row in the CSV file. You need to address the Name field of that row (you also have way too many single- and double-quotes).
foreach ($user in $csv) {Get-ADUser -filter "Name -eq '$($user.name)'"}
Or you could make the CSV file just a vanilla listing of names, and not read it as CSV:
Get-ADGroupMember -identity “Accounting” -recursive | select -expandproperty name | out-file "c:\group.txt"
$csv = get-content -path "c:\group.txt"
foreach ($user in $csv) {Get-ADUser -filter "Name -eq '$user'"}
But if you're only using the file as a conduit between the group search and the user lookup, you can skip that entirely by piping the output of Get-ADGroupMember directly to Get-ADUser.
Get-ADGroupMember -identity “Accounting” -recursive | Get-ADUser;

Related

Finding users in AD

I am trying to use a text file of users e-mail address to find the samaccountname names of the corresponding users.
Clear-Host
Import-Module ActiveDirectory
$File = "C:\T2\Users.csv"
$Users = Get-Content $File
ForEach ($User in $Users)
{ Get-ADUser -Filter * | Where { $_.EmailAddress -eq $User } | Select SamAccountName -ExpandProperty SamAccountName }
I am trying to understand what I am doing wrong
If your file is actually a .csv (comma-separated values), what you're doing is getting raw string content with Get-Content. There is a cmdlet, Import-Csv, that will take your CSV and turn it into a powershell object so you can iterate over it and access the headers as properties like you're trying to do in your code:
$users = Import-Csv -Path '/path/to/file.csv'
Then in your loop, you can clean up and speed up your code by not querying the entire AD tree for each user:
foreach ($user in $users)
{
Get-ADUser -Filter "EmailAddress -eq '$($user.EmailAddress)'" |
Select-Object -ExpandProperty SamAccountName
}
Super simplified version:
#requires -Module ActiveDirectory
foreach ($user in Import-Csv -Path '/path/to/file.csv')
{
(Get-ADUser -Filter "EmailAddress -eq '$($user.EmailAddress)'").SamAccountName
}

Powershell exporting csv issue

<#
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
This script Removes all the groups from Disabled Users (From Disabled OU), It adds the names of those groups to Information Field along with an export of csv with the same information.
Porblem is that the csv is only populated with one user's groupmembership when there are many users in Disabled OU. question is, how do i export all the user and their group membership in a csv format. so i have a list of all the users that have been processed.
I always thought that export-csv will export eveything that powershell processes?
Thanks for your help in advance.
Your script attempts to export a csv for each user:
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 ";"
...
}
However, this will mean that only the last user run in this foreach block will have its data written out to a .csv file.
This is because Export-Csv will overwrite the contents of an existing .csv file by default. So every user in your foreach block will overwrite the user before it.
To fix this, add the parameter switch -Append to the end of your Export-Csv command. This will add on each users data to the end of the file rather than overwrite it e.g.
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
...
}

Get-ADPrincipalGroupMembership : Cannot validate argument on parameter 'Identity'. When i try to delete memberof properties from disabled users

We have a lot of disabled users, I want to write a script to delete the memberof property and keep the default (domain user). The .csv file I'm importing has a list of 5 samaccountname for testing purpose. when I execute this script I get this error message.
I do not get this message when I run the script for individual users but when I import the .csv file with the list of users I receive this error. Thanks for the help in advance.
c:\user\..\Desktop> .\powerAD.ps1
Get-ADPrincipalGroupMembership : Cannot validate argument on parameter 'Identity'. The
argument is null or empty. Provide an argument that is not null or empty, and then try
the command again.
This is the script I wrote:
This there something wrong with my syntax??
Import-Module ActiveDirectory
ForEach ($user in (import-csv -path "C:\users\j\desktop\ADUSER1.csv"))
{
Get-ADPrincipalGroupMembership -Identity $user.samaccountname |
% {Remove-ADPrincipalGroupMembership -Identity $user.samaccountname -MemberOf -confirm:$false $_}
}
.csv file is in this format.
jbry
pbarb
dvan
Screenshot from excel
The issue is your csv file. You are calling for the samaccountname property from it, but no column has that as the column header. Either read it in as a text file with Get-Content or give it a header.
ForEach ($user in (Get-Content "C:\users\j\desktop\ADUSER1.csv")) {
Get-ADPrincipalGroupMembership -Identity $user |
? {$_.Name -ne "Domain Users"} |
% {Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_}
}
Based on comments above and your linked image from Excel, BenH is probably correct. What you need to do now is convert your names, which are strings in PowerShell, into ADUser objects to pass as the -Identity parameter to Get-ADPrincipalGroupMembership and Remove-ADPrincipalGroupMembership:
foreach ($user in (Import-CSV -Path "C:\users\j\desktop\ADUSER1.csv"))
{
$u = Get-ADUser -Filter 'sAMAccountName -eq $user'
$u | Get-ADPrincipalGroupMembership |
Where-Object {$_.name -ne "Domain Users"} |
ForEach-Object {Remove-ADPrincipalGroupMembership -Identity $u -MemberOf $_}
}

PowerShell and getting object properties

Import-Module ActiveDirectory
$users = Get-ADGroupMember -identity “GroupName” | select saMAccountName
foreach($user in $users)
{
}
How can I get 2 properties from here. I need the sAMAccountName and the Office
First, verify if you want to get the "Office" property, or "physicalDeliveryOfficeName"
foreach ($user in $users)
{
Get-ADUser $user -Properties Office | select SamAccountName,Office
}
Also, you don't need to select anything for your $users object to work
$users = Get-ADGroupMember -Identity GroupName
A great thing about working with Active Directory cmdlets is that you can usually throw the entire object at it, and it will work because of:
[parameter(ValueFromPipelineByPropertyName=$true)]
Adding an example that worked for exporting to CSV:
Get-ADUser $user -Properties Office | select SamAccountName,Office | Export-Csv -NoTypeInformation C:\PSResults\foo.csv

Powershell Import-CSV and Foreach-Object, excluding with the CSV header

I'm trying to get the SAMAccountNames of one domain and compare them with their equals from another domain.
To get all users of dc1 I use:
Get-ADUser -Filter * -SearchBase $SearchBase | Select-Object SamAccountName |
Export-Csv -path $exports -encoding "unicode" -notype
and then I import the csv again and try to compare them for any differences
$readthat = Import-CSV $exports -Header SamAccountName | ForEach-Object {
$user1 = Get-ADUser -Identity $_.SamAccountName -Properties $attributes
$user2 = Get-ADUser -Identity $_.SamAccountName -Properties $attributes -Server $dc2
$modified = #{}
$attributes | Where-Object { $user1.$_ -ne $user2.$_ } | ForEach-Object {
$modified[$_] = $user2.$_
}
}
All that works great, except that it's also trying to find the SamAccountName which of course genereates an error because the SamAccountName = SamAccountName doesn't exit.
Any hints on how to avoid this or do you guys have a more elegant solution?
the .csv looks like this:
"SamAccountName"
"foo"
"bar"
Don't use the -Header SamAccountName option on your import-csv should help immensely. The -Header option is for when the CSV file you are importing doesn't have a header. The Export-CSV cmdlet puts the header in there for you, so you don't have to.