-
Notifications
You must be signed in to change notification settings - Fork 14
/
Compress-Data.ps1
73 lines (60 loc) · 4.5 KB
/
Compress-Data.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
function Compress-Data
{
<#
.Synopsis
Compresses data
.Description
Compresses data into a GZipStream
.Link
Expand-Data
.Link
http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx
.Example
$rawData = (Get-Command | Select-Object -ExpandProperty Name | Out-String)
$originalSize = $rawData.Length
$compressed = Compress-Data $rawData -As Byte
"$($compressed.Length / $originalSize)% Smaller [ Compressed size $($compressed.Length / 1kb)kb : Original Size $($originalSize /1kb)kb] "
Expand-Data -BinaryData $compressed
#>
[OutputType([String],[byte])]
[CmdletBinding(DefaultParameterSetName='String')]
param(
# A string to compress
[Parameter(ParameterSetName='String',
Position=0,
Mandatory=$true,
ValueFromPipelineByPropertyName=$true)]
[string]$String,
# A byte array to compress.
[Parameter(ParameterSetName='Data',
Position=0,
Mandatory=$true,
ValueFromPipelineByPropertyName=$true)]
[Byte[]]$Data,
# Determine how the data is returned.
# If set to byte, the data will be returned as a byte array. If set to string, it will be returned as a string.
[ValidateSet('String','Byte')]
[String]$As = 'string'
)
process {
if ($psCmdlet.ParameterSetName -eq 'String') {
$Data= foreach ($c in $string.ToCharArray()) {
$c -as [Byte]
}
}
#region Compress Data
$ms = New-Object IO.MemoryStream
$cs = New-Object System.IO.Compression.GZipStream ($ms, [Io.Compression.CompressionMode]"Compress")
$cs.Write($Data, 0, $Data.Length)
$cs.Close()
#endregion Compress Data
#region Output CompressedData
if ($as -eq 'Byte') {
$ms.ToArray()
} elseif ($as -eq 'string') {
[Convert]::ToBase64String($ms.ToArray())
}
$ms.Close()
#endregion Output CompressedData
}
}