-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDetect-USBStatus.ps1
241 lines (220 loc) · 11.1 KB
/
Detect-USBStatus.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
<#
.SYNOPSIS
Monitor when USB is inserted and removed.
.DESCRIPTION
The script ran in task sechduler on system startup. It monitors a USB letter and Name
If USB removal event is triggered it will shut down the system.
.NOTES
All events are logged
.LINK
https://github.com/PowerShellCrack/USBStatus/edit/master/Detect-USBStatus.ps1
#>
##*===============================================
##* VARIABLE DECLARATION
##*===============================================
[string]$TaskName = "Monitor USB Boot Key - System Startup"
[string]$USBLetter = "I:"
[string]$USBName = "BOOTKEY"
##*===============================================
##* Do not modify section below
$t = '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);'
add-type -name win -member $t -namespace native
[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0)
## Variables: Permissions/Accounts
[Security.Principal.WindowsIdentity]$CurrentProcessToken = [Security.Principal.WindowsIdentity]::GetCurrent()
[Security.Principal.SecurityIdentifier]$CurrentProcessSID = $CurrentProcessToken.User
[string]$ProcessNTAccount = $CurrentProcessToken.Name
[string]$ProcessNTAccountSID = $CurrentProcessSID.Value
[boolean]$IsAdmin = [boolean]($CurrentProcessToken.Groups -contains [Security.Principal.SecurityIdentifier]'S-1-5-32-544')
[boolean]$IsLocalSystemAccount = $CurrentProcessSID.IsWellKnown([Security.Principal.WellKnownSidType]'LocalSystemSid')
[boolean]$IsLocalServiceAccount = $CurrentProcessSID.IsWellKnown([Security.Principal.WellKnownSidType]'LocalServiceSid')
[boolean]$IsNetworkServiceAccount = $CurrentProcessSID.IsWellKnown([Security.Principal.WellKnownSidType]'NetworkServiceSid')
[boolean]$IsServiceAccount = [boolean]($CurrentProcessToken.Groups -contains [Security.Principal.SecurityIdentifier]'S-1-5-6')
[boolean]$IsProcessUserInteractive = [Environment]::UserInteractive
[string]$LocalSystemNTAccount = (New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList ([Security.Principal.WellKnownSidType]::'LocalSystemSid', $null)).Translate([Security.Principal.NTAccount]).Value
# Check if script is running in session zero
If ($IsLocalSystemAccount -or $IsLocalServiceAccount -or $IsNetworkServiceAccount -or $IsServiceAccount) { $SessionZero = $true } Else { $SessionZero = $false }
##*===============================================
##* PATH VARIABLE DECLARATION
##*===============================================
## Variables: Script Name and Script Paths
[string]$scriptPath = $MyInvocation.MyCommand.Definition
[string]$scriptDirectory = Split-Path -Path $scriptPath -Parent
$RunningDate = Get-Date -Format MMddyyyy
If ($SessionZero) {
$FinalLogFileName = ($ScriptName.Trim(" ") + "(SYSTEM)-" + $RunningDate)
} Else {
$FinalLogFileName = ($ScriptName.Trim(" ") + "(" + $env:USERNAME + ")-" + $RunningDate)
}
[string]$Logfile = "$scriptDirectory\Logs\$FinalLogFileName.log"
##*===============================================
##* FUNCTIONS
##*===============================================
Function Write-Log{
[CmdletBinding()]
Param (
[string]$logstring,
[switch]$writehost = $false
)
Add-content $Logfile -value $logstring
If($writehost){
Write-Host $logstring
}
}
#https://powershell.org/2013/04/29/powershell-popup/
Function Show-PopUp{
<#
.SYNOPSIS
Creates a Timed Message Popup Dialog Box.
.DESCRIPTION
Creates a Timed Message Popup Dialog Box.
.OUTPUTS
The Value of the Button Selected or -1 if the Popup Times Out.
Values:
-1 Timeout
1 OK
2 Cancel
3 Abort
4 Retry
5 Ignore
6 Yes
7 No
.PARAMETER Message
[string] The Message to display.
.PARAMETER Title
[string] The MessageBox Title.
.PARAMETER TimeOut
[int] The Timeout Value of the MessageBox in seconds.
When the Timeout is reached the MessageBox closes and returns a value of -1.
The Default is 0 - No Timeout.
.PARAMETER ButtonSet
[string] The Buttons to be Displayed in the MessageBox.
Values:
Value Buttons
OK OK - This is the Default
OC OK Cancel
AIR Abort Ignore Retry
YNC Yes No Cancel
YN Yes No
RC Retry Cancel
.PARAMETER IconType
[string] The Icon to be Displayed in the MessageBox.
Values:
None - This is the Default
Critical
Question
Exclamation
Information
.EXAMPLE
$RetVal = Show-PopUp -Message "Data Trucking Company" -Title "Popup Test" -TimeOut 5 -ButtonSet YNC -Icon Exclamation
.NOTES
FunctionName : Show-PopUp
Created by : Data Trucking Company
Date Coded : 06/25/2012 16:55:46
.LINK
#>
[CmdletBinding()][OutputType([int])]Param(
[parameter(Mandatory=$true, ValueFromPipeLine=$true)][Alias("Msg")][string]$Message,
[parameter(Mandatory=$false, ValueFromPipeLine=$false)][Alias("Ttl")][string]$Title = $null,
[parameter(Mandatory=$false, ValueFromPipeLine=$false)][Alias("Duration")][int]$TimeOut = 0,
[parameter(Mandatory=$false, ValueFromPipeLine=$false)][Alias("But","BS")][ValidateSet( "OK", "OC", "AIR", "YNC" , "YN" , "RC")][string]$ButtonSet = "OK",
[parameter(Mandatory=$false, ValueFromPipeLine=$false)][Alias("ICO")][ValidateSet( "None", "Critical", "Question", "Exclamation" , "Information" )][string]$IconType = "None"
)
$ButtonSets = "OK", "OC", "AIR", "YNC" , "YN" , "RC"
$IconTypes = "None", "Critical", "Question", "Exclamation" , "Information"
$IconVals = 0,16,32,48,64
if((Get-Host).Version.Major -ge 3){
$Button = $ButtonSets.IndexOf($ButtonSet)
$Icon = $IconVals[$IconTypes.IndexOf($IconType)]
}
else{
$ButtonSets|ForEach-Object -Begin{$Button = 0;$idx=0} -Process{ if($_.Equals($ButtonSet)){$Button = $idx };$idx++ }
$IconTypes |ForEach-Object -Begin{$Icon = 0;$idx=0} -Process{ if($_.Equals($IconType) ){$Icon = $IconVals[$idx]};$idx++ }
}
$objShell = New-Object -com "Wscript.Shell"
$objShell.Popup($Message,$TimeOut,$Title,$Button+$Icon)
}
Function Get-ScheduledTasks{
[CmdletBinding()]
Param (
[string]$computername
)
$path = "\\" + $computername + "\c$\Windows\System32\Tasks"
$tasks = Get-ChildItem -Path $path -File
if ($tasks)
{
Write-Verbose -Message "I found $($tasks.count) tasks for $computername"
}
foreach ($item in $tasks)
{
$AbsolutePath = $path + "\" + $item.Name
$task = [xml] (Get-Content $AbsolutePath)
[STRING]$check = $task.Task.Principals.Principal.UserId
if ($task.Task.Principals.Principal.UserId)
{
Write-Verbose -Message "Writing the log file with values for $computername"
Add-content -path $logfilepath -Value "$computername,$item,$check"
}
}
}
##*===============================================
##* MAIN
##*===============================================
$RunningTasks = Get-ScheduledTask -TaskName $TaskName
If (!$SessionZero -and $RunningTasks.State -eq "Running"){
Stop-ScheduledTask -TaskName $TaskName
taskkill /IM powershell.exe /FI "USERNAME eq SYSTEM"
}
Unregister-Event -SourceIdentifier volumeChange -ErrorAction SilentlyContinue
Register-WmiEvent -Class win32_VolumeChangeEvent -SourceIdentifier volumeChange
Write-Log ((get-date -format s) +" Beginning $ScriptName...") -writehost
do{
$newEvent = Wait-Event -SourceIdentifier volumeChange
$eventType = $newEvent.SourceEventArgs.NewEvent.EventType
$eventTypeName = switch($eventType){
1 {"Configuration changed"}
2 {"Device arrival"}
3 {"Device removal"}
4 {"docking"}
}
#Write-Log ((get-date -format s) +" Event detected = "+ $eventTypeName) -writehost
if ($eventType -eq 2){
Write-Log ((get-date -format s) +" USB Key arrival event detected, getting USB details...") -writehost
$driveLetter = $newEvent.SourceEventArgs.NewEvent.DriveName
$driveLabel = ([wmi]"Win32_LogicalDisk='$driveLetter'").VolumeName
Write-Log ((get-date -format s) +" Drive name = "+ $driveLetter) -writehost
Write-Log ((get-date -format s) +" Drive label = "+ $driveLabel) -writehost
# Execute process if drive matches specified condition(s)
if ( ($driveLetter -eq $USBLetter) -and ($driveLabel -eq $USBName) ){
Write-Log ((get-date -format s) +" Starting task in 3 seconds...") -writehost
#Stop-Computer -computerName $env:COMPUTERNAME -force
#start-process "Z:\sync.bat"
}
}
ElseIf ($eventType -eq 3){
$driveLetter = $newEvent.SourceEventArgs.NewEvent.DriveName
if ($driveLetter -eq $USBLetter){
If ($SessionZero) {
Write-Log ((get-date -format s) +" USB Key removal event detected, rebooting system...") -writehost
Stop-Computer -computerName $env:COMPUTERNAME -Force
} Else{
Write-Log ((get-date -format s) +" USB Key removal event detected, sending message...") -writehost
$result = Show-PopUp -Message USB Key ($driveLetter) was removed`n`nSystem shutdown will be triggered in 30 seconds, Continue? -Title USB Key removal -TimeOut 30 -ButtonSet "OC" -IconType "Exclamation"
If ($result -eq 1){ # Accepted
Write-Log ((get-date -format s) +" User accepted, Shutting down system...") -writehost
Stop-Computer -computerName $env:COMPUTERNAME -force
}
ElseIf($result -eq 2){ # Cancelled
Write-Log ((get-date -format s) +" User cancelled system shutdown...") -writehost
}
Else { #Let message continue
Write-Log ((get-date -format s) +" Countdown ended, Shutting down system...") -writehost
Stop-Computer -computerName $env:COMPUTERNAME -force
}
}
}
}
Remove-Event -SourceIdentifier volumeChange
}
while (1 -eq 1) #Loop until next event
Unregister-Event -SourceIdentifier volumeChange