Output on CSV and argument in powershell are not same - powershell

I got user information from the user group in AD. every column has no problem except the user name.
On csv, User name is normal but there is a format when I get content from csv for using powershell like as below;
#{Name=abc}
for compare-object with two CSV, I need to use -expand.
Is there anyway to avoid this result?
I want to get a same content on CSV and powershell.
get-adgroup $path -server server.com | get-adgroupmember -recursive | select-object -unique | get-aduser -properties mail | name, mail | export-csv c:\result.csv

Use import-csv cmdlet to import the csv and not get-content. Also the provided code sample won't work - e.g. you missed select-object here:
| name, mail |
You do not need to query the group, as you already know the name ($path), you can directly query the groupmemberships, e.g.:
get-adgroupmember -identity $path -recursive
But in the end you could achieve the same in a much more efficient way, e.g.:
get-aduser -LDAPFilter "(memberOf:1.2.840.113556.1.4.1941:=[groupDistinguishedName])" -property mail | select-object -property mail,name | export-csv [path]
replace [groupDistinguishedName] with the distinnguishedName of the group. This will give you all users back which are member (transitive) of the defined group.
see: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/4e638665-f466-4597-93c4-12f2ebfabab5

Related

Compare AD users from CSV to a specific OU

I have a CSV list of usernames from all over my domain, and I'm trying to compare the list against a specific OU and send the matches to another file. I'm brand new to powershell, so after a good amount of research and comparing with other scripts I came up with this:
$users = Import-csv C:\Users\me\Desktop\'RSA.csv'
$(ForEach ($user in $users)
{
Get-AdUser -identity $user -SearchBase "ou=Sub,ou=Root,dc=My,dc=Domain,dc=Name" -Filter *
}) |
Select-Object SamAccountName |
Export-CSV -Path C:\Users\me\Downloads\test\output.csv -NoTypeInformation
When I run this I get the error "Get-ADUser : Cannot validate argument on parameter 'Identity'. The Identity property on the argument
is null or empty." If I run without the -identity $user it just pulls everything. Any suggestions on how to make this work?
When you are calling Get-ADUser rather than giving it a string with just the user name you are passing in an object with a property called username. You could use Select-Object -ExpandProperty Username or reference the just property.
Import-Csv 'C:\Users\me\Desktop\RSA.csv' |
Where-Object {(!([string]::IsNullorWhiteSpace($_.UserName)))} |
ForEach-Object {
Get-ADUser -Identity $_.UserName
} |
Select-Object SamAccountName |
Export-CSV -Path C:\Users\me\Downloads\test\output.csv -NoTypeInformation
Notes: Changed to a ForEach-Object loop for readability since it looked like you where trying to mostly use the pipeline. Also added a test to skip blank lines or usernames that are whitespace/empty string. Removed the SearchBase and Filter since you are looking up based on identity can't use those in the command. As there isn't a parameter set that allows you to use all of them. Get-Help Get-ADUser shows the available parameter sets.

Powershell script to display all Users in a Group AD

I have created the below
Get-ADGroup -Filter * -SearchBase "DC=Domain,dc=.com" -properties name, members |
Select-Object *,#{Name='Member';Expression={$_.Members -replace '^CN=([^,]+).+$','$1'}} |
FT Name, Member -Autosize |
out-file c:\text.txt
Ignore Domain and .com I have them populated with my relevant information, but for sake of here removed them.
When I run this it returns what I'm after but when looking at the members within the group they all end with ... and don't show all the members
There are a few things to correct. Let's look at them in order. The actual AD query can be simplified: you only need to specify 'Members' as an additional property to retrieve as 'Name' is brought back by default:
Get-ADGroup -Filter * -SearchBase "DC=Domain,dc=.com" -properties members
Given that you only want to output two properties ('Name' and your custom one 'Member'), use your select to retrieve only the ones you want:
Select-Object Name ,#{Name='Member';Expression={$_.Members -replace '^CN=([^,]+).+$','$1'}}
Remove the Format-Table: we have already limited the selection in the previous command. Format cmdlets are designed to format the output to the console window and best practice dictates that they should only be used for that purpose and that they should always be the last element of a pipeline.
Piping all of that to Export-Csv will then produce what you want:
Export-Csv -NoTypeInformation -Path C:\text.csv
This one did the trick for me
Get-ADGroupMember -Identity Administrators | Select-Object name, objectClass,distinguishedName | Export-CSV -Path “adgroupmembers.csv”
I got this here.
https://www.lepide.com/how-to/export-members-of-a-particular-ad-group-using-poweshell.html#:~:text=The%20PowerShell%20Get%2DADGroupMember%20cmdlet,group%20you%20want%20to%20use.

Powershell pipe variables into get-user command

I am trying to pipe a list of email addresses into a get-user command in powershell
$email = get-content -path "c:\temp\file.csv" get-user -indentity $email | select-object userprincipalname,department,phone,name | format-table | out-file c:\temp\file.txt
Welcome to SO.
Lets see... where to start
Email Address is not one of the value recognized for Identity
It is spelled -identity
Don't use Format-table for object output.
Department is not one of the default values returned.
There is no AD attribute just called phone
It's Get-Aduser not get-user
Don't know if it was just a copy paste accident but you have multiple lines as one.
-Identity expects one value. Not an array of names.
Knowing that lets see if we can take a stab at what you were trying to do. Assuming that your file "c:\temp\file.csv" only contained addresses with no header (since that is how you were treating it.)
Get-Content c:\temp\file.csv | ForEach-Object{
Get-ADUser -Filter "emailaddress -eq '$_'" -Properties department,OfficePhone
} | Select-Object UserPrincipalName,Department,OfficePhone,Name | Export-CSV C:\temp\outputfile.csv -NoTypeInformation
There is no error correction here so you might need to look into an -ErrorAction try/catch combination. I encourage you to look that up on your own.

Powershell ActiveDirectory Logging and import for easy rollback

Im writing a custom script from start to finish to search for users ,so i can disable and move them. (script is done and working)
What im trying to do now is to create a easy readable log which also has to be used as an easy rollback.
I.ex.:
Get-Aduser -Identity test -properties SamAccountName,MemberOf,GivenName,Surname
This will return something in line of:
DistinguishedName : CN=test,OU=OUy,OU=Lab Accounts,DC=domain,DC=org
Enabled : True
GivenName : test
Name : test
SamAccountName : test
Surname : test
Memberof : {CN=OU,OU=Norway,OU=Lab Accounts,DC=Domain,DC=org, CN=Domain Admins,CN=Users,DC=Domain,DC=org}
If i use:
$test2 = Get-ADUser -Identity test |
Select-Object -Property SamAccountName,GivenName,Surname,Memberof
which gives me:
SamAccountName GivenName Surname Memberof
-------------- --------- ------- --------
test test test {}
What my issue now is how to log this to either a csv/text file which can be easily imported back for rollback.
Im currently using clixml which preserves the export ive done with a hashtable within a hashtable.
like:
$user=#{
#{
Username=$user.samaccountname
Memberof=$user.memberOf
}
}
This allows me to more or less use dot notation to access the information stored for easy rollback, but viewing the file is not that easy readable
Which method do you propose me to use to log the info i need when alot of the info is some kind of collection of items?
I've tried to explore with PSobject but i havent gotten the hang of that yet.
Are there any logging method which will output to a easy to read log and easy use for rollback?
If anyone is able to supply an example and also point me to a page to further explore this i will appreciate it very much.
By readerfriendly im thinking of something like this:
Username,Givenname,Surname,Memberof
Test,test2,test3,Admins;somegroup;somegroup
or
Username,Givenname,Surname,Memberof
Test,test2,test3,Admins somegroup somegroup
EDIT 1
Here is the code that gets the info:
Get-ADUser -Identity test -Properties SamAccountName,GivenName,Surname,Memberof |
Select-Object -Property SamAccountName,GivenName,Surname,Memberof | export-csv C:\test.txt
This is what is in the file as output:
#TYPE Selected.Microsoft.ActiveDirectory.Management.ADUser
"SamAccountName","GivenName","Surname","Memberof"
"test","Mari","Hopkins","Microsoft.ActiveDirectory.Management.ADPropertyValueCollection"
You already have this information primed for a CSV. Why not just use Export-CSV and the opposite Import-CSV
$test2 | Export-CSV -Path c:\temp\backup.csv -Append
Append will add the item to the file and not overwrite the current contents. Then, if you need to, you can import it back with Import-CSV. Likely with multiple objects
$deprecatedAccounts = Import-CSV -Path c:\temp\backup.csv
To create the output you could collect the users with an array.
$users = #()
$users += $test2
$users | Export-CSV -Path c:\temp\backup.csv -Append
Edit from comments
Sorry, I didnt understand the issue at first. What you need to do is expand MemberOf from an array to a string.
Get-ADUser test -Properties SamAccountName,GivenName,Surname,Memberof |
Select-Object SamAccountName,GivenName,Surname,#{Label="MemberOf";Expression = {$_.Memberof -join ";"}} |
Export-Csv -Path c:\temp\backup.csv -Append -NoTypeInformation
Create a calculated property in the select-object that expands the memberof into a semicolon delimeted string. -NoTypeInformation removes the #TYPE Selected.Microsoft.ActiveDirectory.Management.ADUser line if you do not like that.
If you ever needed to process this back into an array you could do so with a simple split
Import-CSV c:\temp\backup.csv | ForEach-Object{$_.MemberOf -split ";"}
Depends on what you mean by easy to read, but how about using Export-Clixml to store the object and Import-Clixml to import it?

Powershell script:how to Filter on AD Get commands to return certain information

I am trying to create a powershell script that checks AD group membership/domain/manage by etc amongst other information and puts into csv file, because I want to structure the csv file in a certain way how do i filter within the actual script to only return certain information e.g. withe the code below its returning a lot more columns but from these the only ones i want are "managed by" and "name":
Get-ADDomain -property managed By, Name|Export-csv -path C:\AD\Domain.csv -NoTypeInformation
Use -Properties to specify the properties you want, and then pipe to Select-Object to select the properties you want in the output. For example:
get-aduser -filter * -properties canonicalName,userPrincipalName |
select-object canonicalName,userPrincipalName |
export-csv myfile.csv -notypeinformation
Get-ADDomain doesn't have -Properties but you can still use Select-Object:
get-addomain | select-object ManagedBy,Name | export-csv myfile.csv -notypeinformation