Last weekend I’ve been asked to write a script that will output the size of all files within a folder, and the files in all its sub-folders.
So, again something that’s possible with a one-liner
Get-ChildItem D:\Software -recurse | Select-Object Name, @{Name=”KiloBytes”;Expression={$_.Length / 1KB}}
You don’t want the output to be in Kb but in MB? No problem…
Get-ChildItem D:\Software -recurse | Select-Object Name, @{Name=”MegaBytes”;Expression={$_.Length / 1MB}}
You can create script blocks for KB and MB ahead of time
$mb=@{Name=”MB”;Expression={($_.length/1MB)}}
$kb=@{Name=”KB”;Expression={($_.length/1kb)}}
Then use them as you need depending on the folder: dir c:files | select fullname, $mb
or even format the number
$mb=@{Name=”MB”;Expression={“{0:F2}” -f ($_.length/1MB)}}
Script blocks are definitely the way to go when you’re building a script since you can use them multiple times later in the script, but for a one-liner I can’t think of a reason to use it… or am I forgetting something?
I was merely suggesting defining scriptblocks so you could reuse them in other one liners. Suppose you want to check a diffierent folder and you want this to be in MB, just the the MB scriptblock in the select statement. I’m just trying to save some typing.
Then we are in agreement 🙂 Your feedback and tips are always welcome btw…
coming full circle: Re-Use #PowerShell Scriptblocks https://plus.google.com/109354722869529171746/posts/RGideinCBTo
Jeff : if you dont mind can you just give some brief about this line @{Name=”MegaBytes”;Expression={$_.Length / 1MB}} is this supposed to be a hash table ? am not understanding how this works
Hi Arun,
What happens there is that I’ve created a custom property with the name “MegaBytes” and expression (value) of the length of the file and devide that by 1MB so that it will provide an output in the MB size.
This is a custom property, not a hash table since that doesn’t allow you to customize the property name for example: http://technet.microsoft.com/en-us/library/ee692803.aspx
Does that anwser your question?
Jeff.