Using PowerShell Desired State Configuration to Unzip Files
A couple of months ago I wrote a blog about a PowerShell Function to Unzip Files Using the .NET Framework 4.5 with Fallback to COM. I've since discovered that the new Desired State Configuration (DSC) feature in PowerShell version 4 can unzip files. You probably wouldn't use this feature just to unzip a single file to a single server, but it does open up some interesting possibilities.
This blog article is not meant to be an all inclusive tutorial on DSC, it's only meant to give you a peek inside the built-in DSC Archive Resource capabilities.
First, define your DSC configuration to create your MOF (Managed Object Format) file:
1configuration UnZipFile {
2
3 param (
4 [Parameter(Mandatory=$True)]
5 [string[]]$ComputerName,
6
7 [string]$Path,
8 [string]$Destination
9 )
10
11 node $ComputerName {
12
13 archive ZipFile {
14 Path = $Path
15 Destination = $Destination
16 Ensure = 'Present'
17
18 }
19
20 }
21
22}
Notice that by parameterizing the configuration, I'm able to use my parameters instead of having to rewrite the configuration each time:
Voila! MOF file created:
1UnzipFile -ComputerName Server01 -Path \\dc01\Share\ServerAdd.zip -Destination C:\
Since I defined the ComputerName parameter as mandatory, if I forget to specify that parameter I'll be prompted for a value for it. I can also specify more than one value and create multiple MOF files for different nodes, all with a single command:
Now I'll apply this configuration to Server01 to place it in the desired state:
1Start-DscConfiguration UnZipFile -ComputerName Server01 -Wait -Verbose
The first time I ran this command, I thought there was a problem with the archive file due to the messages about files missing or not being a file. This is actually DSC checking the destination to see if the files already exist.
I removed one of the files and reapplied the state to confirm that the messages about files missing are indeed about the destination and not the source:
What I really like is that reapplying the state only extracted the one missing file and not the entire archive since all of the other files already existed.
µ