It’s possible to compress a folder or file since Windows NT. It’s a feature of the NTFS-filesystem. Normally we would do that on the properties of the folder or file in the Windows Explorer, but you can do this with PowerShell too! Just use this command:

Invoke-WmiMethod -Path "Win32_Directory.Name='C:\Test'" -Name compress

And to Uncompress the same folder, use this command:

Invoke-WmiMethod -Path "Win32_Directory.Name='C:\Test'" -Name uncompress

We’re talking about NTFS compression here, not the ZIP-feature introduced in Windows XP and later. You can notice that the folder is compressed by the blue color of the folder in Windows Explorer. Or you can open the properties of the folder to see whether the size on disk is smaller than the normal size. Do not try to compress items that are already compressed, like pictures (JPG…), music (MP3…), video (AVI, MPG…).

When you use WMI to execute operating system functions like this, you get a return value. When the return value is 0 (zero) this means the command functioned. Other return values can mean different things (read-only, no disk space, no permissions,…). In general: when we’re executing WMI-commands we’re allways checking the return value. You could implement it like this:

$a = Invoke-WmiMethod -Path "Win32_Directory.Name='C:\Test'" -Name compress
If ($a.returnvalue) -eq 0 { "Items successfully compressed" } else { "Something went wrong!" }

 

2 Comments on Compress a folder or file using PowerShell

  1. Alegro Firany says:

    There is apparently a bunch to know about this. I feel you made various good points in features also.

  2. alban.lopez@gmail.com says:

    Very cool code, but not work on UNC network path

Leave a Reply