File Compression
Before I draw this article to a close, we will look briefly at one more pair of file operations that can be executed with methods of CIM_DataFilenamely, those concerned with compression. Unsurprisingly, these operations are carried out by Compress() and Uncompress(), neither of which takes any parameters. Although these methods barely warrant a script example of their own, I will present one nonetheless as an excuse to consolidate some of the issues discussed so far in this part of the articlenamely, error handling and consistency. The following script retrieves a CIM_DataFile object representing the file c:\temp\albatross.txt, compresses it if it is not already compressed, decompresses it if it is compressed, and reports its success. Notice that immediately after a successful call to Compress() or Uncompress(), you dereference the object, precluding the possibility of any consistency errors, even though you know you will not make any mistakes in a script this simple.
'compress.vbs - toggle compression status of a file Set refFile = GetObject("winMgmts:CIM_DataFile='c:\temp\albatross.txt'") If Not refFile.Compressed then If refFile.Compress = 0 Then WScript.echo "File compressed successfully" Set refFile = Nothing Else WScript.echo "File could not be compressed" End If Else If refFile.Uncompress = 0 Then WScript.echo "File uncompressed successfully" Set refFile = Nothing Else WScript.echo "File could not be uncompressed" End If End If 'if we were to invoke a property of refFile here we may get a runtime error 'if refFile has been set to nothing, but we know that we will never get 'incorrect information Set refFile = Nothing