12

#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.

filecompression

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()
Filed in: Columns, Tips and Tricks Tags: , ,

12 Responses to "#PSTip Compress and uncompress files and folders using WMI"

  1. pamarths says:

    Nice tip. I will try this.

  2. Jon Gross says:

    Nice tip. Much simpler than any other “tips” I found. They make good functions.

  3. Jeffrey Snover says:

    I like the CIM method of doing this:

    Invoke-CimMethod –Query ‘select * from CIM_DataFile where name = “C:\Temp\test.txt”‘ –MethodName “Compress”

    Invoke-CimMethod –Query ‘select * from CIM_DataFile where name = “C:\Temp\test.txt”‘ –MethodName “UnCompress”

    Jeffrey Snover [MSFT]
    Distinguished Engineer

  4. RameshK says:

    Didn’t work for me. I tried to compress a sqlaudit log file using the compress command listed above. I can only see the attribute change from ‘A’ to ‘AC’. on Windows2008r2. Where as if I use windows compress utility I get the 52 Meg file to 3 Meg.

  5. Mitch says:

    It is a lot of overhead to use the SELECT * when only the name field is used. This should provide better performance:

    $file = Get-WmiObject -Query “SELECT name FROM CIM_DataFile WHERE Name=’C:\\scripts\\test.vhd'”
    $file.Compress()

    $file = Get-WmiObject -Query “SELECT name FROM CIM_DataFile WHERE Name=’C:\\scripts\\test.vhd'”
    $file.Uncompress()

    $folder = Get-WmiObject -Query “SELECT name FROM CIM_Directory WHERE Name=’C:\\scripts'”
    $folder.Compress()

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: