Have you ever found yourself in a situation where you wanted to export the output of a PowerShell cmdlet or script, but needed to add an extra column to the output to export to a CSV file?
Without a better idea you started the regular foreach loop, just to build a pscustomobject that you could export, right? Worry no more, there's a much simpler way!
Use the @{name=''; expression={}} method!
Let's see how it works!
Example - 1
Let's start with a simple example, exporting a file list with the file name and size in MB measurements.
# Get the size in MB using the 'ls' command ls c:\temp\blob.txt | select name,@{name="Size in MB"; expression={$_.length / 1MB}}
Example - 2
Or another, more practical example: from time to time you might need to export mailbox sizes from your Exchange environment. You might have noticed that the Get-MailboxStatistics command is what returns the active mailbox size in it's TotalItemSize property.
However the same cmdlet only has a DisplayName property to identify the mailbox. If you need the UserPrincipalName or any other mailbox attributes together with the size, do the following:
Start with the Get-Mailbox cmdlet, get all the attributes you need (in this case the UPN) and use a custom property to return the mailbox size:
# Export the UserPrincipalName and the mailbox size values for mailboxes Get-Mailbox alice | select userprincipalname, @{name = "Size"; expression = {(Get-MailboxStatistics $_).totalitemsize}}
Enjoy 🙂
Comments