Foreach loop to get department name in powershell office365 - powershell

I am trying to get the department from a list of UserPrincipalNames
I am able to get this to work for a single user outside of the foreach loop. Its adding the loop where I am having trouble.
Connect-MsolService
$users = Import-Csv C:\Users\me\Desktop\users.csv
foreach ($user in $users){
Get-MsolUser -UserPrincipalName $user | Select-Object firstname, lastname, UserPrincipalName, department |Export-Csv C:\Users\me\Desktop\test.csv
}
There are 50 email addresses listed in the CSV one email address per line. With the first line being "UserPrincipalName"
CSV Sample Data
userprincipalname
useremail1#mydomain.com
useremail2#mydomain.com
useremail3#mydomain.com
useremail4#mydomain.com

Think PowerShell - the pipeline uses objects, and you have a ForEach-Object cmdlet:
Connect-MSOLService
Import-CSV -Path C:\Users\Me\Desktop\Users.CSV |
ForEach-Object { Get-MSOLUser -UserPrincipalName $_.UserPrincipalName |
Select-Object firstname, lastname, UserPrincipalName, department } |
Export-CSV C:\Users\Me\Desktop\test.CSV

In case you need to lookup for data from a csv , then want to use them in a script and export scrip 's result in another CSV
# Importing MsOnline Module
Import-Module MSOnline
Connect-MsolService
#Import excel document containing our data ,Path "C:\list-email.csv"
$ImportData = Import-Csv "C:\list-email.csv"
$Output = foreach ( $Data in $ImportData )
{
#Storing Email column data in $Data for each row
write-host $Data.Email
Get-MsolUser -UserPrincipalName $Data.IONEmail | Select-Object UserPrincipalName,LastPasswordChangeTimestamp, Departement
}
#Output the array to the CSV File
$Output | Export-CSV "C:\LastLogonDateExport.csv"

Related

Populate Data into a Specific column in CSV Powershell

So I'm trying to add values to a CSV file. The code below works however it places the value in $department at the bottom of the file, but in the correct column. Does anyone have any advice on how I can get the value from $deparment to append to the top of the column in the CSV? My code is below:
$users = Import-Csv $file -Delimiter ","
$column_number = 6
foreach($user in $users){
$name = $user.Name
$department = Get-ADUser -Identity $name -Properties Department | Select-Object -ExpandProperty Department
Add-Content $file -Value "$(","*$column_number)$department"
}

Exporting Membership groups for users from input file

I have this script that reads samaccountnames from a file and outputs the name of the user with its membership information. However, the output file only shows the last record. It seems that my code is overwriting the previous record. What am I missing? Thank you so much.
ForEach ($user in $(Get-Content -Path C:\MyScripts\UsersInput.csv))
{
$username = Get-ADUser –Identity $user -Properties *
Get-ADPrincipalGroupMembership $user | select $username.DisplayName, name |
export-csv "C:\MyScripts\UsersAndTheirADGroups.csv" -NoTypeInformation
}
Export-Csv has an -append parameter, so you could use that. ie it would append to the csv file with every iteration of the loop. You would need to make sure the file didn't exist before you start the loop or it would just get bigger and bigger each time you ran the code.
Another way it to add the items to an object and then export that at the end. ie $username += Get-ADUser......
You are reading a CSV file using Get-Content. This lets me think the file is simply a list of user SamAccountNames, each on a separate line. No headings.
Something like this perhaps:
jdoe
jsmith
If that is the case, read the input file like this:
$users = Get-Content -Path 'C:\MyScripts\UsersInput.csv'
To get an array of user SAMAccountnames.
If however it is a proper CSV file with headers, looking something like this:
"SamAccountName","Email","More","Stuff"
"jdoe","john.doe#yourdomain.com","blah","blah"
"jsmith","jane.smith#yourdomain.com","blah","blah"
Then you should use the Import-Csv cmdlet to get the entries as objects and obtain an array of SamAccountNames from that:
$users = Import-Csv -Path 'C:\MyScripts\UsersInput.csv' | Select-Object -ExpandProperty SamAccountName
Once you have that array, loop through it and get the group membership info for each user
Untested
$result = foreach ($accountName in $users) {
Get-ADUser –Identity $accountName -Properties DistinguishedName, DisplayName |
Select-Object #{Name = 'User'; Expression = {$_.DisplayName}},
#{Name = 'Groups'; Expression = { ( $_ | Get-ADPrincipalGroupMembership | Select-Object -ExpandProperty name) -join ', '}}
}
$result | Export-Csv "C:\MyScripts\UsersAndTheirADGroups.csv" -NoTypeInformation
You are indeed overwriting the code ForEach user. You included Export-Csv in the ForEach. Instead export the whole array that ForEach creates:
ForEach ($user in $(Get-Content -Path C:\MyScripts\UsersInput.csv))
{
$username = Get-ADUser –Identity $user -Properties *
Get-ADPrincipalGroupMembership $user | select $username.DisplayName, name
} | export-csv "C:\MyScripts\UsersAndTheirADGroups.csv" -NoTypeInformation

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.

Powershell Compile all matching rows from CSV

I have a CSV file with a list of Users and who they are managed by with these headers:
DisplayName,Alias,CA5,Managedby
I want to import this list in powershell and be able to send one email to each manager with the list of accounts (DisplayName,Alias,CA5) that they are listed as the manager of in the managedby field. I can create the email with out issue I need to know how to compile all the lines of the CSV file that should all go to into the same email. With the sample CSV below I should end up with three emails (one each to ManagedByA, ManagedbyB and ManagedByC). The email to ManagedByA would have three lines containing:
DN1 A1
DN2 A2 DL
DN3 A3
My CSV look like this:
DisplayName,Alias,CA5,ManagedBy
DN1,A1,,ManagedByA
DN2,A2,DL,ManagedByA
DN3,A3,,ManagedByA
DN4,A4,,ManagedByB
DN5,A5,,ManagedByB
DN6,A6,DL,ManagedByB
DN7,A7,,ManagedByB
DN8,A8,,ManagedByC
DN9,A9,DL,ManagedByC
DN10,A10,,ManagedByC
My Code (from Mathias R. Jessen):
$Import = Import-CSV "C:\powershell\DL\Reports\DLReportEmail.csv"
### Find unique ManagedBy
$Managers = $Import | Sort-Object -Property ManagedBy -Unique
ForEach ($Manager in $Managers){
$Employees = $Import | Where-Object {$_.ManagedBy -eq $Manager.ManagedBy}
$Body = "DearXXXX, `r`n"
ForEach($Employee in $Employees){
$Alias = $Employee.Alias
$DisplayName = $Employee.DisplayName
$CA5 = $Employee.CA5
$Body += "$DisplayName : $Alias : $CA5 `r`n"
}
$Body += "`r`n"
$Body += "Thanks"
You can import the csv, extract each unique manager name, and then compile a subset of the list by using the ManagedBy values you've already extracted:
$Users = Import-Csv C:\filename.csv
$Managers = $Users | Sort-Object -Property ManagedBy -Unique
for($Manager in $Managers)
{
$Employees = $Users |Where-Object {$_.ManagedBy -eq $Manager.ManagedBy}
// send your email here with the contents of $Employees
}

Writing an array to a specific csv column with powershell

I have a csv file that has a lot of data in it, with one column being a "Username" column. I created a loop to query AD and get each username and now I need to export each of those names to the specific column in the csv. After importing the csv with:
$data = Import-CSV .\data.csv
And using the loop:
foreach($user in $data)
And I use get-aduser $user -server $server and if($? -eq $true){ $user = $user + "01" }
I tried using
$data.Username | Export-CSV .\data.csv and $data.Username | out-file .\data.csv
but so far neither have worked.
You need to keep all the information in the pipeline so you can re-export the whole thing.
Try something like this:
$data | Foreach {
get-aduser $_.Username -server $server
if($? -eq $true){ $_.Username = $_.Username + "01" }
} | export-csv .\data.csv