I have the following script that outputs a color coded folder hierarchy of a user’s Exchange mailbox. It output the line in red if it’s over a certain threshold (20 MB in this case) and gray if not.
#Get Folder Size Breakdown to Table with Color Coding
get-mailbox $username |
Get-MailboxFolderStatistics |
ft @{
Name="Name"
Expression=
{
$prefix=""
foreach($c in $_.FolderPath.ToCharArray())
{
if($c -eq '/'){$prefix+='-'}
}
if($_.FolderSize -gt 20MB)
{
$Host.UI.RawUI.ForegroundColor = "Red"
} else
{
$Host.UI.RawUI.ForegroundColor = "Gray"
}
$prefix + $_.Name
}
},
FolderSize,
FolderandSubfolderSize
There are a few problems with this script.
If the last folder processed is larger than 20 MB, my console text remains Red after it runs.
This script assumes that the original console text was Gray. If it’s not Gray, then I’ve changed the user’s console text.
Both of these are very easy to resolve if you’re not in the context of a format-table expression, but I can’t for the life of me figure out if it’s possible to resolve these issues in this particular case. Here’s the gist of what I’ve tried but it doesn’t work. (In reality I’ve tried about 20 different variations).
get-mailbox $username |
Get-MailboxFolderStatistics |
ft @{
Name="Name"
Expression=
{
$prefix=""
$originalColor = $Host.UI.RawUI.ForegroundColor
foreach($c in $_.FolderPath.ToCharArray())
{
if($c -eq '/'){$prefix+='-'}
}
if($_.FolderSize -gt 20MB)
{
$Host.UI.RawUI.ForegroundColor = "Red"
}
$prefix + $_.Name
$Host.UI.RawUI.ForegroundColor = $originalColor
}
},
FolderSize,
FolderandSubfolderSize
Note: The purpose of this is to eventually compress this down to a one-liner. I know that I can store the variable before I start the pipeline and the restore the color after the pipeline is finished, but that takes the fun/aggravation out of it. I’m more curious as to whether or not I can accomplish this without altering the basic structure of this pipeline.
I don’t think this is possible. Essentially, every time
Format-Tablereads the Expression forNamethe foreground color will change. ButFormat-Tableprobably doesn’t write out the value from that expression immediately, so you can’t reset the color in the expression.I think you’re going to have to wrap your pipeline:
Another option would be to write your own formatting code that finds the maximum size of each column then uses
Write-Hostto write things out: