Private/Test-IdoItCacheFile.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
83
84
85
86
87
Function Test-IdoItCacheFile {

    <#
   .SYNOPSIS
   This function tests if a cache file exists and/or is valid.

   .DESCRIPTION
   This function tests if a cache file exists and/or is valid. If the file does not exist or the cache duration is not valid anymore
   the function will return $False

   .PARAMETER CacheType
   CacheType defines wich type of cache to be written.

   .PARAMETER Expiry
   Expiry is a TimeSpan that defines how old the cache file is allowed to be

   .EXAMPLE
   PS> Test-IdoItCacheFile -CacheType Constant -Expiry (New-Timespan -Days 30)

   This will test for the Constant cache file and test if the content is not older than 30 days
   If you do not provide Expiry parameter the function will only test if the file exists

   .NOTES
   Version
   0.1.0 20.01.2018 CB initial release
   #>


   [CmdletBinding ()]
   Param (
       [Parameter (
           Mandatory = $True
       )]
       [ValidateSet('Constant','Config')]
       [String]$CacheType,

       [Parameter (
           Mandatory = $False
       )]
       [Timespan]$Expiry
   )

   Begin {

           $CachePath = $env:LOCALAPPDATA+"\.psidoit"
           $CacheFile = $CachePath + "\$CacheType.json"

   }
   Process {

       Try {

            If ( -Not (Test-Path $CacheFile ) ) {

                Return $False

             }

             If ( $PSBoundParameters.ContainsKey('Expiry') ) {

                $CacheData = Get-Content -Path $CacheFile -Raw | ConvertFrom-Json


                $TimeSpan = New-TimeSpan -Start ([Datetime]::parseexact($CacheData.CreationTime, "o", $Null))
                Write-Verbose "Age of the cache file content is $TimeSpan"

                If ($TimeSpan -gt $Expiry) {
                    Return $False
                }

             }

             Return $True


       }
       Catch [Exeption] {

           Throw $_

       }

   }

}