Exporting CSV with different data - powershell

I'm attempting to extract licencing information via o365 with the current script:
Foreach($User in $Users){
$UPN = $User.UserPrincipalName
Get-MsolUser -UserPrincipalName "$UPN" | Select-Object DisplayName,Licenses | Export-Csv -Append -Path c:\test\$exportpath.csv -NoTypeInformation
}
I'm noticing I'm getting two different outputs, whenever I run this via ISE I'll get the following:
However, when I look at the exported CSV I get the following:
So my question is how exactly should I set this up so when I extract information and export it into a CSV that it'll capture all information and not simply state it as a generic list?

Your license field is actually a list of multiple licenses and you need to 'expand' this out before you export to csv. You should be able to do this with a join function or you can iterate through foreach loop.
Get-MsolUser -All | Select-Object office,#{name="licenses";expression={$_.licenses.accountskuid}},userprincipalname | Export-Csv .\licenses.csv -NoTypeInformation

Related

Output on CSV and argument in powershell are not same

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

I have a .csv with thousands of emails, and I need to use Active Directory to find the state of a particular, custom variable, using powershell

I'm new and don't know enough about powershell.
I've got a .csv that is nothing but "EMAILS" for the header and some 6000 emails under it. (email1#company, email2#company, etc.)
I need to find the state of a particular, custom property for each one.
Individually, I know that I can run
Get-ADUser -Filter {mail -eq 'email#company'} -properties customproperty
in order to find one particular user's state.
I have been hitting my head against a wall trying to make it work with import-csv and export-csv, but I keep getting red all over my console.
Can someone point me an to example where import-csv and export-csv are used properly, with a command run against the contents?
Here's what I would do.
First, fetch all users that have email addresses in AD, and save them into a hashtable. This will make lookups absurdly faster and place less overall load on your domain controller. If you've got 100,000 user accounts it may not be the best option, but I expect that it will be in general.
$ADUsers = #{};
Get-ADUser -Filter "mail -like '*'" -Properties mail, customproperty | ForEach-Object {
$ADUsers.Add($_.mail, $_.customproperty);
}
Now you import the CSV and do lookup using a calculated property with Select-Object, and export it back out.
Import-Csv -Path $InputFile | Select-Object -Property emails, #{n='customproperty';e={$ADUsers[$_.emails]}} | Export-Csv -Path $OutputFile -NoTypeInformation;
So without seeing the code of what you posted, where I think you will run problems is with how interaction of two things.
The first will be that when you use the Import-CSV cmdlet. You will receive an array of objects with a property for each column and not an array of strings.
This is ties into the second part of the issue which is the sensitivity of the AD module filter. But the short answer is don't use {} inside the filter because it will break if you use {mail -eq $ImportedCSV.EMAILS}.
mklement0 has a wonderful answer that goes into the details. But a simple rule of thumb is "double quote outer, single quote" inner.
So you could expand the EMAILS property either with Select-Object -ExpandProperty EMAILS to have an array which works inside {} or you could use "mail -eq '$ImportedCSV.EMAILS'".
Here is an example with both the expansion and using the "property -eq '$variable'" style filter:
Import-CSV C:\Example\Path.csv |
Select-Object -ExpandProperty EMAILS |
ForEach-Object {
Get-ADUser -Filter "mail -eq '$_'" -Properties customproperty
} |
Select-Object mail,customproperty |
Export-CSV C:\Example\OutputPath.csv -NoTypeInformation
Please use below code
$csvInput = Import-CSV C:\Example\test.csv
Foreach ($line in $csvinput) {
Get-ADUser -Filter {mail -eq $line.mail} -Properties mail, customproperty |
Select-Object mail,customproperty |
Export-CSV C:\Example\OutputPath.csv -NoTypeInformation
}

Adding AD group members to CSV list of AD groups

I have a list of AD security groups contained in a .csv file, in the following format:
Groups,
Groupname1,
Groupname2,
Groupname3,
What I want to do is feed this .csv file to a PowerShell script, so it can report on the group membership of the groups listed in the .csv file (I don't care about recursive groups, as I don't have any). The script should then dump the results to a further .csv file.
So, ideally, I want the final .csv produced output from the scripts to be something like.
Groupname1, name
Groupname1, name
Groupname2, name
Groupname2, name
Groupname3, name
Groupname3, name
You get the idea.
What I am struggling with is getting some sort of for loop going, to look through all the groups from the .csv and output the results as shown above (groupname and then user).
$list = Import-Csv -Path C:\temp\ADGroups.csv
foreach ($groups in $list) {
$ADGroup = $groups.groupname
Get-ADGroupmember -Identity $ADGroup | Get-ADUser -Property Name
Export-Csv -Path "c:\temp\dump.csv"
}
I've seen other suggestions (see example here), but these don't read the groups from a .csv file.
You need to add the group name to the output. I would do this with a calculated property. You also need to move the Export-Csv outside the loop or use -Append. If not, the groups will overwrite the file every time and it will only contain the results from the last group. Try this:
Import-Csv -Path C:\temp\ADGroups.csv | Foreach-Object {
$ADGroup = $_.Groups
Get-ADGroupmember -identity $ADGroup | Select-Objects #{n="Groupname";e={$ADGroup}}, Name
} | Export-CSV -Path "c:\temp\dump.csv" -NoTypeInformation

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