#PSTip Compress and uncompress files and folders using WMI
Note: This tip requires PowerShell 2.0 or above.
In WMI, the CIM_DataFile and CIM_Directory classes have some very useful methods we can use. For example, the Compress() and the Uncompress() methods can be used to reduce the on-disk footprint of a file or a folder. Essentially, think of this as a poor man’s compression toolkit! These methods use NTFS compression.
In today’s tip, I will show you how you can use these methods to work with file/folder compression. There are multiple ways we can invoke WMI methods in PowerShell. For the purpose of this tip, I will stick to calling the methods on a WMI object using the dotted notation.
$file = Get-WmiObject -Query "SELECT * FROM CIM_DataFile WHERE Name='C:\\scripts\\test.vhd'" $file.Compress()
The above code snippet compresses the file. To uncompress, we simply use the the Uncompress() method.
$file = Get-WmiObject -Query "SELECT * FROM CIM_DataFile WHERE Name='C:\\scripts\\test.vhd'" $file.Uncompress()
The Compressed property of CIM_DataFile instance tells us if the file is compressed or not.
To see if a file is really compressed or not, we can verify its size on the disk.
Now, how do we compress a folder? Simple. We use the Compress() method of a CIM_Directory instance.
$folder = Get-WmiObject -Query "SELECT * FROM CIM_Directory WHERE Name='C:\\scripts'" $folder.Compress()