-
Notifications
You must be signed in to change notification settings - Fork 1
/
Watch-Here.ps1
86 lines (77 loc) · 2.43 KB
/
Watch-Here.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
<#
.Synopsis
Watch for new files
.DESCRIPTION
Watch a target path for new files
.EXAMPLE
Watch-Here -Wait
The file 'test - Copy.txt' was Created at 06/12/2015 11:13:08
The file 'New Text Document.txt' was Created at 06/12/2015 11:13:20
.EXAMPLE
Watch-Here
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
28 Created NotStarted False ...
.EXAMPLE
$Job = Watch-Here -Path 'C:\temp\Share\*' -Action { mv 'C:\temp\Share\*' 'C:\private'; write-host "Moved share to private" }
#>
function Watch-Here
{
[CmdletBinding()]
Param
(
# Specifies the path to watch
[Parameter(ValueFromPipelineByPropertyName=$true,
Position=0)]
$Path = $PSScriptRoot
, # Specify a filesystem filter script
[string]
$Filter = "*"
, # Event Type
[ValidateSet("Created", "Changed", "Renamed", "Deleted")]
[string]
$EventName = "Created"
, # Show events in the console
[switch]
$Wait
, # Include Subdirectories
[switch]
$Recurse
, # Action
[scriptblock]
$Action = {
$Name = $Event.SourceEventArgs.Name
$Type = $Event.SourceEventArgs.ChangeType
$Time = $Event.TimeGenerated
Write-Output "$Time`: $Type the file '$Name'"
}
)
Begin
{
$event = Get-EventSubscriber -SourceIdentifier $EventName -ErrorAction SilentlyContinue
if($event){
Unregister-Event -SourceIdentifier $EventName -Confirm
}
}
Process
{
$Watch = New-Object IO.FileSystemWatcher $Path, $Filter -Property @{
IncludeSubdirectories = $Recurse
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
$handler = Register-ObjectEvent -InputObject $watch -EventName $EventName -SourceIdentifier $EventName -Action $Action
if($Wait)
{
<#
Use try/finally to catch the script being killed with "Ctrl-C" and unregister the event listener.
End {} Will not be called when ended this way.
#>
try { Wait-Event $EventName }
finally { Unregister-Event $EventName }
}
}
End
{
Write-Output $handler
}
}