Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

Re-Use PowerShell Scriptblocks

Posted on October 24, 2011November 18, 2011

//Re-Use PowerShell Scriptblocks//

I commented on a blog post today that showed how to use a hash table with Select-Object to format file sizes say as KB.

dir $env:temp -rec | select fullname,@{Name="KB";Expression={$_.length/1kb}}

Since you most likely will want to use something similar for other directories, don't feel you have to re-invent the wheel. Save the hashtable as a scriptblock. Here are some examples:

$KB=@{Name="SizeKB";Expression={$_.length/1kb}}
$MB=@{Name="SizeMB";Expression={$_.length/1mb}}
$GB=@{Name="SizeGB";Expression={$_.length/1gb}}

Now, you can get formatted sizes

dir ~documents -recurse | select fullname,$mb
dir e:vboxdisks -recurse | select name,$gb | format-table -auto

Or if you want to format the number, just update the hash table:

$MB=@{Name="SizeMB";Expression={"{0:F2}"-f ($_.length/1mb)}}

If you define these ahead of time, you can reuse them as needed depending on how you want to format the data.

What other custom scriptblock suggestions do you have?

Share this:

  • Print (Opens in new window) Print

Like this:

Like Loading…

Related

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2026 The Lonely Administrator | Powered by SuperbThemes!
%d