Functions/Private/Get-RoboSize.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
74
75
76
77
78
79
80
81
82
function Get-RoboSize {
    [cmdletbinding()]
    param(
        [Parameter(
            Position = 0,
            Mandatory = $true
        )]
        [string]
        $Path,

        [Parameter(
        Mandatory = $false
        )]
        [int]
        $DecimalPrecision = 2,

        [Parameter(
        Mandatory = $false
        )]
        [int]
        $Threads = 16
    )

    if (Get-Command -Name 'robocopy') {

        Write-Verbose -Message "Using robocopy to get size of path -> [$Path]"

        $args = @(
            "/L",
            "/S",
            "/NJH",
            "/BYTES",
            "/FP",
            "/NC",
            "/NDL",
            "/TS",
            "/XJ",
            "/R:0",
            "/W:0",
            "/MT:$Threads"
        )

        [DateTime]$startTime = [DateTime]::Now

        Write-Verbose "Running -> [robocopy $($Path) NULL $($args)] <-"
        [string]$summary     = robocopy $Path NULL $args | Select-Object -Last 8
        [DateTime]$endTime   = [DateTime]::Now
        [regex]$headerRegex  = '\s+Total\s*Copied\s+Skipped\s+Mismatch\s+FAILED\s+Extras'
        [regex]$dirRegex     = 'Dirs\s*:\s*(?<DirCount>\d+)(?:\s+\d+){3}\s+(?<DirFailed>\d+)\s+\d+'
        [regex]$fileRegex    = 'Files\s*:\s*(?<FileCount>\d+)(?:\s+\d+){3}\s+(?<FileFailed>\d+)\s+\d+'
        [regex]$byteRegex    = 'Bytes\s*:\s*(?<ByteCount>\d+)(?:\s+\d+){3}\s+(?<BytesFailed>\d+)\s+\d+'
        [regex]$timeRegex    = 'Times\s*:\s*(?<TimeElapsed>\d+).*'
        [regex]$endRegex     = 'Ended\s*:\s*(?<EndedTime>.+)'

        Write-Verbose "Raw summary:"
        Write-Verbose ($summary | Out-String)

        $expectedSummary = "$headerRegex\s+$dirRegex\s+$fileRegex\s+$byteRegex\s+$timeRegex\s+$endRegex"
        if ($summary -match $expectedSummary) {

            $roboObject = [PSCustomObject]@{
                
                Path        = $Path
                TotalBytes  = [decimal]$Matches['ByteCount']
                TotalKB     = [math]::Round(([decimal] $Matches['ByteCount'] / 1KB), $DecimalPrecision)
                TotalMB     = [math]::Round(([decimal] $Matches['ByteCount'] / 1MB), $DecimalPrecision)
                TotalGB     = [math]::Round(([decimal] $Matches['ByteCount'] / 1GB), $DecimalPrecision)
                TimeElapsed = [math]::Round([decimal] ($endTime - $startTime).TotalSeconds, $DecimalPrecision)

            }

            return $roboObject

        }

    } else {

        throw "Robocopy command is not available... cannot continue!"

    }
}