Loop through Search-mailbox - powershell

I have a requirement to search mailboxes for an email based on subject line and report if the email is in the Inbox or another folder. The below code works well for individual users.
Search-Mailbox -Identity "test#example.com" -SearchQuery ‘Subject:”Suspect email alert”‘ -TargetMailbox “admin” -TargetFolder “inbox”-LogOnly -LogLevel Full
The report received states if the email is in that particular mailbox and the location. This is great for one user, though I need to do this for over 500 users.
I have a csv file with a list of email addresses I need to check for this particular email and it's location. So I have imported the csv file to a variable. Then put the command in a foreach loop, though cannot get this working correctly.
Correction: updated to txt file a used get-content
$users = Get-Content -Path userslist.txt
foreach ($user in $users) {
Search-Mailbox $user -SearchQuery ‘Subject:”Suspect email alert”‘ -TargetMailbox “admin” -TargetFolder “inbox”-LogOnly -LogLevel Full }
How do I run through the list of users, so I can get one report rather than a report for each user individually. Any ideas would be great.

Issue was with the csv file formatting. imported text file and loop running fine. Would be good to get the results into one Search results file, rather than one for each loop.

Related

Exporting multi-valued attributes to new lines on a CSV

A bit of background on this.
I have approx 900 user accounts in active directory that are disabled and need to be deleted. They all have mailboxes attached, and to prevent these email addresses being recycled and reused for new users, I want to add each email address, along with any email aliases to a distribution group that essentially won't go anywhere.
I have a list of the FQDNs off all 900 users, and I have created a script in Powershell that will take my list, and then it will do a "for each" loop for each user. The script gathers their email addresses and then exports them to a CSV file.
The end goal is to have a long list of email addresses so that I can add them to the distribution group.
Because the emailaddresses attribute has multiple values, I'm finding that when it exports it to excel, it exports each email address to the same line, currently separated by a semicolon.
What I am looking to achieve, is for each individual email address to be listed on a brand new line on the export. Is this possible?
# Get list of users that we want to delete.
$Users = Get-Content "c:\temp\UsersToDelete.txt"
# For each user - find their email addresses and append them to a CSV.
foreach ($User in $Users) {
Get-Mailbox -Identity "$User" | select #{Name=’emailaddresses’;Expression={$_.emailaddresses -join “;”}} | export-csv -append "c:\temp\CollectedEmailAddresses.csv"
}
You would need an inner loop for each value in the .emailaddresses property:
Get-Content "c:\temp\UsersToDelete.txt" | ForEach-Object {
foreach($email in (Get-Mailbox -Identity $_).emailaddresses) {
[pscustomobject]#{
User = $_
Email = $email
}
}
} | Export-Csv "c:\temp\CollectedEmailAddresses.csv" -NoTypeInformation
Also your code would be more efficient moving Export-Csv as the last statement in your pipeline and removing -Append assuming this is a new file. Appending a CSV line per loop iteration is inefficient and only slowing down your script.

Powershell: Pulling from a list (CSV) running a command and outputting to a different CSV

very new to heavier powershell and I've been hacking at this all day and can't figure it out.
I need to get a list of UPNs from office 365 accounts. I have the names in a CSV file. It has one column, with a long list of names. Heading is "name"
I want to run the get-user command against every name with the pipe format-list name, universalprincipalname and then output it to a new file.
I tried this:
get-content "m:\filename.csv" |
foreach {get-user '$_.user' -identity -resultsize unlimited} |
format-list name, userprincipalname |
out-file -FilePath m:\newfilename.csv
But it did not work (I also tried it with import-csv). It seemed to instead of pulling from my list, pull right from the office365 exchange server and when it finally finished had way more names in it than I have in my list.
My overall goal is to generate a list of upns of all the people who do not have mobile devices with their account so I can use a powershell command to disable active sync and OWA for mobile devices. Unfortunately, the command I used to generate my list of users produced the list in first name, last name format...and we have so many users I can't just concatenate the thing in excel, because there would be a ton of mistakes.
CSV is laid out like this:
Column1
name
first last
first last
first last
first last
Assuming the CSV's header is Name, the code should look like this:
Import-Csv "m:\filename.csv" | ForEach-Object {
Get-User -Identity $_.Name.Trim() -ResultSize Unlimited
} | Select-Object Name, UserPrincipalName |
Export-Csv "m:\newfilename.csv" -NoTypeInformation
Note that I'm using Select-Object instead of Format-Table. You should only use Format-Table to display your output to the PowerShell host, objects passed through the pipeline to this cmdlet will be recreated into a new object of the type FormatEntryData which you do not want if your intent is to export the data.

Getting All Calendar SubFolders from CSV List of Users

I am trying to get a list of all the subfolders for a list of users from importing a CSV. Here is the code I have:
Import-Csv "C:\Users\177626\Desktop\Calendar.csv" | foreach {Get-MailboxFolder -identity "$($_.CalendarUsers):\Calendar" -GetChildren}
$_.CalendarUsers is what I am using as the column in the CSV for the user email addresses.
The issue is whenever I run the script, it reads the first users but then tell me any user after that, that the mailbox does not exist. See attached:
Any help would be much appreciated to figure this out...also, is it possible to also list the User's Name and PrimarySMTP from the output of this script?
Thanks!
Please check if all the mailboxes and the calendars in the .csv file are provisioned.
Import-Csv "C:\Users\177626\Desktop\Calendar.csv" | foreach {Get-Mailbox -identity $_.CalendarUsers}
Import-Csv "C:\Users\177626\Desktop\Calendar.csv" | foreach {Get-MailboxCalendarFolder -Identity "$($_.CalendarUsers):\Calendar"}
ref: https://learn.microsoft.com/en-us/powershell/module/exchange/get-mailboxcalendarfolder?view=exchange-ps

Who to email based on attachment file

Without using a ton of ElseIf statements is it possible to select the the recipient of an email based on the file that will be attached to the email while iterating over all files in a folder?
I have started building this without the foreach get-ChildItem running over the folder where I create the email object, assign specific recipients, and choose a specific file out of the folder, but this is quite tedious and repetitive. I feel like there has to be a way to use an array of arrays or something where based on the file that the loop is on it pulls through the recipients and maybe a custom subject line.
There's tons of powershell email code out there so I won't repost that. Just not sure how to even attack this.
One option would be to have an accompanying CSV file, with rows for the filename, the recipient and the subject name etc. You could then import the CSV file using Import-Csv.
For example:
$emailList = Import-csv c:\users.csv
foreach ($line in $emailList) {
Write-Host "Sending message to $($line.emailAddress)"
Send-MailMessage -To $line.emailAddress `
-Subject $line.subject `
-Attachments $line.attachmentPath `
-Body $line.bodyText
}
and if you wanted to define the contents of the CSV in the PowerShell script, rather than using an external file, you could do something like:
$emailList = "emailAddress,subject,attachmentPath,bodyText
joe#bloggs.com,Attachment for Joe,c:\attachmentsToSend\joe.pdf,Attached is your file
Mary#bloggs.com,Mary's attachment,c:\attachmentsToSend\mary.pdf,Hello, Mary. Attached is your file
" | ConvertFrom-Csv
Put that above the foreach loop in the script

Import .csv AzureADUser script only returns 100 entries

I have exported a list of 270 user accounts from O365, all my shared mailboxes, what I want to do is pull the department field of each of those accounts.
But the output from cmdlet Get-Mailbox which I used to get my sharedlist.csv doesn't include the department information.
I know AzureADUser does, so, I am trying to loop through the sharedlist.csv and pull the displayname, UPN, and Department for each addresses listed in the sharedlist.csv
What I'm trying to figure out is how to have Get-AzureADUser pull only the information on the users I have listed in my CSV file.
Here is the command that I have so far:
Import-Csv 'C:\PowerShell Scripts\sharedlist.csv' | ForEach {Get-AzureADUser -All $True | Select-Object DisplayName,UserPrincipalName,Department}
This is obviously not working for what I'm trying to do. It outputs in the format I want and shows the data, but it is pulling every Azure Ad User and then looping over and over. If someone can point me to the proper syntax needed to get this job done I'd appreciate it.
TIA
As Lee_Daily already explained in his comment, you are using the Get-AzureADUser cmdlet without any parameter, so it returns info about any user, not only the ones you have defined in the CSV file.
If your file (I peeked in the original question) looks like this:
"UserPrincipalName"
"user1#domain.com"
"user2#domain.com"
"user270#domain.com"
Then this should work for you:
$data = Import-Csv 'C:\PowerShell Scripts\sharedlist.csv'
$data | ForEach-Object {
Get-AzureADUser -ObjectId $_.UserPrincipalName | Select-Object DisplayName,UserPrincipalName,Department
}