header image

COM pt 5–FileSystem Object

Posted by: | January 31, 2011 | No Comment |

I haven’t finished with the WScript.Shell object and we will return to it.  This time I want to look at the FileSystem object. If you have worked with VBScript and files you will be familiar with this object.  While we have techniques in PowerShell to perform many of the same tasks there are still a few places where using this object can save effort.

For instance getting the size of  folder.  We can use get-childitem and use measure-object on the output but that gets a bit messy. An alternative is to do this

$fso = New-Object -ComObject "Scripting.FileSystemObject"
$top = $fso.GetFolder("c:\test")
"{0,-20} {1,12}" -f $top.Path, $top.Size
foreach ($sf in $top.SubFolders) {
"{0,-20} {1,12}" -f $sf.Path, $sf.Size


Create the FileSystem object and get the folder we are interested in.  Display the Path and Size properties.

we can then use the SubFolders collection to loop through the and get the path and size of each sub folder.

This is only the first level sub folders – if we want more we need to think about recursion

under: COM, PowerShellV2