TimestompUtils.psm1

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<#
.SYNOPSIS
    Return a .NET DateTime object that falls within a specified range.
     
    Vasken Houdoverdov
    https://github.com/vhoudoverdov/
 
.DESCRIPTION
    Part of a module that facilitiates the generation of random DateTime objects and the modification of FileInfo objects to the resulting dates.
.EXAMPLE
    New-RandomDate
#>
 

Function New-RandomDate {
$Ceiling = Get-Date -Year 2020 -Month 12 -Date 31
$Floor = Get-Date -Year 2000 -Month 12 -Date 31
Return $(New-Object DateTime($(Get-Random -Max $Ceiling.Ticks -Min $Floor.Ticks))).ToUniversalTime()
}

<#
.SYNOPSIS
    Utility for timestomping files in the specified path.
    Several properties of object type System.IO.FileInfo are modified as a result.
     
    Vasken Houdoverdov
    https://github.com/vhoudoverdov/
 
.DESCRIPTION
    Part of a module that facilitiates the generation of random DateTime objects and the modification of FileInfo objects to the resulting dates.
 
.Example
    Timestomp-Files -Path $Path
 
.Example
    Timestomp-Files -Path $Path -Modified -Accessed -Created
 
.Example
    Timestomp-Files -Path $Path -TargetDate $DateTimeObject
#>
 

Function Timestomp-Files {
Param([string]$Path,
      [Datetime]$TargetDate,
      [Switch]$Modified,
      [Switch]$Accessed,
      [Switch]$Created
     )

if($TargetDate -eq $NULL) {

if ($Path -isnot [System.IO.DirectoryInfo]){  
if($Modified)
{
$(Get-Item $Path).LastWriteTime = $(New-RandomDate)
$(Get-Item $Path).LastWriteTimeUTC = $(New-RandomDate)
}

if($Accessed)
{
$(Get-Item $Path).LastAccessTime = $(New-RandomDate)
$(Get-Item $Path).LastAccessTimeUTC = $(New-RandomDate)
}

if($Created)
{
$(Get-Item $Path).CreationTime = $(New-RandomDate)
$(Get-Item $Path).CreationTimeUTC = $(New-RandomDate)}
}

else
{  
if(!$(Test-Path $Path)){throw "The specified path wasn't found: $Path"}
if(!$(Test-Path "$Path\*")){throw "The specified path was empty: $Path"}
}
}

else
{
    if ($Path -isnot [System.IO.DirectoryInfo])
    {  
        if($Modified)
        {
            $(Get-Item $Path).LastWriteTime = $TargetDate
            $(Get-Item $Path).LastWriteTimeUTC = $TargetDate
        }

    if($Accessed)
        {
            $(Get-Item $Path).LastAccessTime = $TargetDate
            $(Get-Item $Path).LastAccessTimeUTC = $TargetDate
        }

    if($Created)
        {
            $(Get-Item $Path).CreationTime = $TargetDate
            $(Get-Item $Path).CreationTimeUTC = $TargetDate
        }
}

    else
    {
        if(!$(Test-Path $Path)){throw "The specified path wasn't found: $Path"}
        if(!$(Test-Path "$Path\*")){throw "The specified path was empty: $Path"}

    }
}
}