Getting Calculated Expression to Display Properly in Powershell Exchange Command - email

So I have a command to look at all the mailboxes in my environment and return the oldest item in any folder that is not the "Contacts" folder of that particular mailbox. The whole thing seems to work except for the calculated expression that I threw in at the end of the command:
#{Name="Address";Expression={Get-Mailbox | ForEach-Object {$_.PrimarySmtpAddress}
The problem is this seems to return every Smtp Address for each line/object instead of one Smtp Address per line/object.
Here's the entire command:
Get-Mailbox | ForEach-Object {Get-MailboxFolderStatistics -IncludeOldestandNewestItems -Identity $_.Alias | Where-Object {($_.OldestItemReceivedDate -ne $null) -and ($_.FolderPath -ne "/Contacts")} | Sort OldestItemReceivedDate | Select First 1 OldestItemReceivedDate, Identity, #{Name="Address";Expression={Get-Mailbox | ForEach-Object {$_.PrimarySmptAddress}}}}
Ideally this would return the date of the oldest item, the folder where it was found, and the primary SMTP Address but it doesn't seem to be pulling only the corresponding SMTP Address. It looks like it's pulling every Primary SMTP Address every iteration. I'm sure it's something with my command but I can't figure out where. Any help would be much appreciated.

The calculated expression has access to the current pipeline object. However you are not using that when creating your expression. You are just calling every mailbox for each user as you have seen. Use the current pipeline object with $_. Get-Mailbox is smart enough to match needed values by property name.
#{Name="Address";Expression={Get-Mailbox $_ | ForEach-Object {$_.PrimarySmtpAddress}}}}
However you might be able to go about this is a different way. You already called all mailboxes at the start of your pipeline. No sense calling it a second time again.
Get-Mailbox | Select-Object Identity, #{Name="Address";Expression={$_.PrimarySmtpAddress}}, #{Name="OldestItemReceivedDate";Expression={
Get-MailboxFolderStatistics -IncludeOldestandNewestItems -Identity $_.Alias | Where-Object {
($_.OldestItemReceivedDate -ne $null) -and ($_.FolderPath -ne "/Contacts")} |
Sort-Object OldestItemReceivedDate |
Select-Object -ExpandProperty OldestItemReceivedDate -Last 1
}}
Now we have 2 calculated properties and we only need to call Get-Mailbox once for each user. You have some spelling mistakes and logic errors that I tried to fix. You will know if it does what you want.

Related

Powershell Custom column returning empty value with certain cmdlets

When adding a custom column with the get-mailbox cmdlet i get an empty value.
I'm trying to add a custom column using select #{} on the get-mailbox cmdlet. no matter what i tried the result is always an empty value, i changed the original cmdlet and replaced it with say get-process and then it did work.
I even tried with explicitly providing a username and not relying on the pipeline variable, and it didn't work.
get-mailbox <username> | select name, #{name="size"; expression={Get-MailboxStatistics $_.samaccountname | select -ExpandProperty TotalItemSize}}
Thanks in advance for any help.
Edit 1: The reason my question is not the same as Powershell script with Get-Mailbox and Get-MailboxStatistics missing output, as in the mentioned question the person was getting some results from their custom columns, just they were having issues with one row on one column, i don't even get results on the second or third rows.
Edit 2: I know i can create my own object, but i was trying to not to have to, this above code should be working (in a perfect world atleast). also the reason i'm not piping directly, i would've but i was trying to present my question with the least code possible to make it easier for the community to replicate it and to dissect it, the actual code i wanted to run is this
get-mailbox <username> | Get-MailboxStatistics | select displayname,TotalItemSize,#{name="Archive size";expression={Get-MailboxStatistics $_.samaccountname -archive | select -ExpandProperty TotalItemSize}}
My end goal was to get a table with a list of users with their mailbox size and their archive size.
Edit 3: never mind, i tried creating my own object and the same issue persisted. Provided my code used for the object.
get-mailbox <username> | foreach {[pscustomobject]#{name = $_.name; "mailbox size" = Get-MailboxStatistics $_.samaccountname | select -expand TotalItemSize; "Archive size" = Get-MailboxStatistics $_.samaccountname -archive | select -expand TotalItemSize}}
Thanks again!
Got it. Your code read like this:
get-mailbox <username> | Get-MailboxStatistics | select displayname,TotalItemSize,#{name="Archive size";expression={Get-MailboxStatistics $_.samaccountname -archive | select -ExpandProperty TotalItemSize}}
has an error. Your expression includes reference to samaccountname which is in Get-Mailbox output but not in Get-MailboxStatistics output, thus you're querying a null mailbox. To fix, query archive mailbox with a displayName attribute.
get-mailbox <username> | Get-MailboxStatistics | select displayname,TotalItemSize,#{name="Archive size";expression={Get-MailboxStatistics $_.displayname -archive | select -ExpandProperty TotalItemSize}}

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
}

PowerShell Office 365 Script to get user and mailbox information together

I am brand new to PowerShell (started this morning). I have successfully connected to my Office 365 and have been able to get lists of users from Office 365 and mailbox fields from the Exchange portion. What I can't figure out is how to combine them.
What I am looking for is the ability to export certain fields from the mailbox object but only for those mailboxes that belong to a non-blocked, licensed Office 365 users. We have a lot of users whose mailboxes have not been removed but they may no longer be licensed or they may be blocked.
Here are the two exports I have running now. They are complete exports. I tried to filter to the Office 265 users by isLicensed but I never got any results so I just downloaded everything and post processed them with Excel. But I need to run this on a regular basis...
Here's the code:
Get-Mailbox -ResultSize Unlimited | Select-Object DisplayName,Name,PrimarySMTPAddress,CustomAttribute2 | Export-CSV C:\temp\o365\mailboxes.csv
Get-MsolUser -all | Select-Object SignInName, DisplayName, Office, Department, Title, IsLicensed | export-csv c:\temp\o365\Users.csv
Any assistance would be appreciated.
Okay, so as I understand what you're trying to do... You want to get a list of all O365 users for whom the IsLicensed property is $true and the BlockCredential property is $false. Of those users, you then want to pull some data from their mailbox objects; DisplayName, Name, PrimarySMTPAddress, and CustomAttribute2.
There are a couple of ways that we can do this. The first is easier to throw together in the shell but takes longer to actually run. The second requires some set up but completes quickly.
First method
Since we know what our criteria is for what we want from Get-MsolUser, we'll use the pipeline to pull out what we want and toss it straight into Get-Mailbox.
Get-MsolUser -All | Where-Object {$_.IsLicensed -eq $true -and $_.BlockCredential -eq $false} |
Select-Object UserPrincipalName |
ForEach-Object {Get-Mailbox -Identity $_.UserPrincipalName | Select-Object DisplayName,Name,PrimarySMTPAddress,CustomAttribute2}
O365 PowerShell doesn't like giving us ways to filter our initial query, so we handle that in the second step, here...
Where-Object {$_.IsLicensed -eq $true -and $_.BlockCredential -eq $false}
This means, for each item passed in from Get-MsolUser -All, we only want those which have the properties Islicensed set to $true and BlockCredential set to $false.
Now, we only care about the results of Get-MsolUser in so far as determining what mailboxes to look up, so we'll grab a single property from each of the objects matching our prior filter.
Select-Object UserPrincipalName
If you only run everything up to this point, you'd get a list of UPNs in your shell for all of the accounts that we're now going to pipe into Get-Mailbox.
Moving on to our loop in this... If you haven't learned ForEach-Object yet, it's used to run a scriptblock (everything between the {}) against each item in the pipeline, one at a time.
Get-Mailbox -Identity $_.UserPrincipalName
Welcome to the pipeline operator ($_). Our previous Select-Object is feeding a collection of objects through the pipeline and this placeholder variable will hold each one as we work on them. Since these objects all have a UserPrincipalName property, we reference that for the value to pass to the Identity parameter of Get-Mailbox.
Sidebar
Here's a simple example of how this works..
PS> 1,2,3 | ForEach-Object {Write-Host $_}
1
2
3
Each item is passed along the pipeline, where we write them out one at a time. This is very similar to your standard foreach loop. You can learn more about their differences in this Scripting Guy post.
Moving on...
Select-Object DisplayName,Name,PrimarySMTPAddress,CustomAttribute2
We wrap it up with one last Select-Object for the information that you want. You can then look at the results in the shell or pipe into Export-Csv for working with in Excel.
Now... Since the pipeline works sequentially, there's some overhead to it. We're running a command, collecting the results, and then passing those results into the next command one at a time. When we get to our Get-Mailbox, we're actually running Get-Mailbox once for every UPN that we've collected. This takes about 2.5 minutes in my organization and we have less than 500 mailboxes. If you're working with larger numbers, the time to run this can grow very quickly.
Second method
Since a large amount of the processing overhead in the first method is with using the pipeline, we can eliminate most of it by handling our data collection as early and thoroughly as possible.
$Users = Get-MsolUser -All | Where-Object {$_.IsLicensed -eq $true -and $_.BlockCredential -eq $false} | Select-Object -ExpandProperty UserPrincipalName
$Mailboxes = Get-Mailbox | Select-Object UserPrincipalName,DisplayName,Name,PrimarySMTPAddress,CustomAttribute2
$Results = foreach ($User in $Users) {
$Mailboxes | Where-Object UserPrincipalName -eq $User
}
$Results | Export-Csv myFile.csv
The first 2 lines are pretty self-explanatory. We get all the user account info that we care about (just the UPNs) and then we grab all the mailbox properties that we care about.
foreach ($User in $Users)
Each entry in $Users will be stored in $User, where we'll then use it in the scriptblock that follows (in the {}).
$Mailboxes | Where-Object UserPrincipalName -eq $User
Each item in $Mailboxes is piped into Where-Object where we then check if the UserPrincipalName property is equal to the current value of $User. All of the matches are then stored in $Results, which can again be piped to Export-Csv for work in Excel.
While this method is harder to write out in the shell, and requires a little extra initial set up, it runs significantly faster; 22 seconds for my org, versus 2.5 minutes with the first method.
I should also point out that the use of UserPrincipalName with the mailbox dataset is simply to help ensure a solid match between those and the account dataset. If you don't want it in your final results, you can always pipe $Results into another Select-Object and specify only the properties that you care about.
Hope this helps!

Import-CSV and Foreach to use Get-ADUser

I have a CSV file that looks like this:
name
fname1lname1#companyemail.com
fname2lname2#companyemail.com
...
I would like to loop through each email address and query AD for that address to grab the user objects ID. I have been able to do this using a script, but I would like to be able to do it using just one line.
This is what I've done so far:
import-csv -path .\csv_file.csv | foreach-object { get-aduser -filter { proxyaddresses -like "*$_.name*} | select name } | out-file .\results.csv
This obviously doesn't work and I know it has something to do with how I am handling my $_ object in the foreach loop.
I'm hoping for the output to look something like:
fname1lname1#companyemail.com,userID1
fname2lname2#companyemail.com,userID2
...
You are filtering on the property proxyaddresses however that is not part of the default property set that Get-AdUser returns. Also your code had a errant " which might have been a copy paste error.
Import-CSV -Path .\csv_file.csv | ForEach-Object {
Get-ADUser -Filter "ProxyAddresses -like '*$($_.name)*'" -Properties ProxyAddresses,EmailAddress | select EmailAddress,SamAccountName
} | Export-CSV .\results.csv -NoTypeInformation
-Filter can be tricky sometimes as it is looking for string input. Wrap the whole thing in quotes and use a sub expression to ensure that the variable $_.Name is expanded properly and has is asterisks surrounding it.
Since you are also looking for emailaddress we add that to the properties list as well. I will assume the second column is for samaccountname.
We also use Export-CSV since that will make for nice CSV output.
If you're using Exchange this can be much simpler and faster if you use the Exchange cmdlets:
Import-CSV -Path .\csv_file.csv | ForEach-Object {
Get-Recipient $_ |
Select PrimarySMTPAddress,SamAccountName
} | Export-CSV .\results.csv -NoTypeInformation
Exchange requires all email address to be unique, and maintains it's own internal database that uses email address as a primary index so it can return the DN and SamAccountName that goes with that email address almost immediately.
AD doesn't require them to be unique, so it doesn't index on that attribute and it has to search every user object looking for the one that has that email address in it's proxy address collection.

List all mailboxes that forward to a specific user

I have this script that lists all mailboxes that are forwarding email, however, I am curious if there would be a way to make it return all mailboxes that forward to a specific user. Basically I'm trying to find out every mailbox that forwards mail to "johndoe". Any help would be greatly appreciated! This is for exchange 2007 btw...
Here's the script so far:
$fwds = get-mailbox | Where-Object { $_.ForwardingAddress -ne $null }
| select Name, ForwardingAddress
foreach ($fwd in $fwds) {$fwd | add-member -membertype noteproperty
-name “ContactAddress” -value (get-contact $fwd.ForwardingAddress).WindowsEmailAddress}
$fwds
Exchange uses CanonicalName for the forwarding address, so you'll need to look that up from the user name. Since it could be a Mailbox, DL, or Contact, the easiest way I know of is to use Get-Recipient, and grab the Identity property.
$RecipientCN = (get-recipient johndoe).Identity
get-mailbox | Where-Object { $_.ForwardingAddress -eq $RecipientCN }
#mjolinor's version works, but is rather slow, since it loads all the mailboxes. On my system it took about 30 seconds to go through ~300 mailboxes.
This can be speed up by adding a filter to the Get-Mailbox command to only return ones that are actually being forwarded, like so:
$RecipientCN = (get-recipient johndoe).Identity
Get-Mailbox -ResultSize Unlimited -Filter {ForwardingAddress -ne $null} | Where-Object {$_.ForwardingAddress -eq $RecipientCN}
But wait, we can get even faster! Why not search for the correct user right in the filter? Probably because it's hard to get the syntax right, because using variables in -Filter gets confusing.
The trick is to use double quotes around the entire filter expression, and single quotes around the variable:
$RecipientCN = (get-recipient johndoe).Identity
Get-Mailbox -ResultSize Unlimited -Filter "ForwardingAddress -eq '$RecipientCN'"
This version returns the same results in 0.6s - about 50 times faster.