|
| 1 | +<# |
| 2 | +.SYNOPSIS |
| 3 | +
|
| 4 | +.DESCRIPTION |
| 5 | +
|
| 6 | +.NOTES |
| 7 | +.LINK |
| 8 | +
|
| 9 | +#> |
| 10 | +##*=============================================== |
| 11 | +##* VARIABLE DECLARATION |
| 12 | +##*=============================================== |
| 13 | +$t = '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);' |
| 14 | +add-type -name win -member $t -namespace native |
| 15 | +[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0) |
| 16 | +## Variables: Permissions/Accounts |
| 17 | +[Security.Principal.WindowsIdentity]$CurrentProcessToken = [Security.Principal.WindowsIdentity]::GetCurrent() |
| 18 | +[Security.Principal.SecurityIdentifier]$CurrentProcessSID = $CurrentProcessToken.User |
| 19 | +[string]$ProcessNTAccount = $CurrentProcessToken.Name |
| 20 | +[string]$ProcessNTAccountSID = $CurrentProcessSID.Value |
| 21 | +[boolean]$IsAdmin = [boolean]($CurrentProcessToken.Groups -contains [Security.Principal.SecurityIdentifier]'S-1-5-32-544') |
| 22 | +[boolean]$IsLocalSystemAccount = $CurrentProcessSID.IsWellKnown([Security.Principal.WellKnownSidType]'LocalSystemSid') |
| 23 | +[boolean]$IsLocalServiceAccount = $CurrentProcessSID.IsWellKnown([Security.Principal.WellKnownSidType]'LocalServiceSid') |
| 24 | +[boolean]$IsNetworkServiceAccount = $CurrentProcessSID.IsWellKnown([Security.Principal.WellKnownSidType]'NetworkServiceSid') |
| 25 | +[boolean]$IsServiceAccount = [boolean]($CurrentProcessToken.Groups -contains [Security.Principal.SecurityIdentifier]'S-1-5-6') |
| 26 | +[boolean]$IsProcessUserInteractive = [Environment]::UserInteractive |
| 27 | +[string]$LocalSystemNTAccount = (New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList ([Security.Principal.WellKnownSidType]::'LocalSystemSid', $null)).Translate([Security.Principal.NTAccount]).Value |
| 28 | +# Check if script is running in session zero |
| 29 | +If ($IsLocalSystemAccount -or $IsLocalServiceAccount -or $IsNetworkServiceAccount -or $IsServiceAccount) { $SessionZero = $true } Else { $SessionZero = $false } |
| 30 | + |
| 31 | + |
| 32 | +[string]$ScriptName = "Monitor USB Boot Key" |
| 33 | +[string]$ScriptVersion= "1.0" |
| 34 | + |
| 35 | +$RunningDate = Get-Date -Format MMddyyyy |
| 36 | +If ($SessionZero) { |
| 37 | + $FinalLogFileName = ($ScriptName.Trim(" ") + "(SYSTEM)-" + $RunningDate) |
| 38 | +} Else { |
| 39 | + $FinalLogFileName = ($ScriptName.Trim(" ") + "(" + $env:USERNAME + ")-" + $RunningDate) |
| 40 | +} |
| 41 | +[string]$Logfile = "E:\Data\Processors\Logs\$FinalLogFileName.log" |
| 42 | + |
| 43 | +##*=============================================== |
| 44 | +##* FUNCTIONS |
| 45 | +##*=============================================== |
| 46 | +Function Write-Log{ |
| 47 | + [CmdletBinding()] |
| 48 | + Param ( |
| 49 | + [string]$logstring, |
| 50 | + [switch]$writehost = $false |
| 51 | + ) |
| 52 | + Add-content $Logfile -value $logstring |
| 53 | + If($writehost){ |
| 54 | + Write-Host $logstring |
| 55 | + } |
| 56 | +} |
| 57 | +Function Show-PopUp{ |
| 58 | +<# |
| 59 | + .SYNOPSIS |
| 60 | + Creates a Timed Message Popup Dialog Box. |
| 61 | + .DESCRIPTION |
| 62 | + Creates a Timed Message Popup Dialog Box. |
| 63 | + .OUTPUTS |
| 64 | + The Value of the Button Selected or -1 if the Popup Times Out. |
| 65 | + Values: |
| 66 | + -1 Timeout |
| 67 | + 1 OK |
| 68 | + 2 Cancel |
| 69 | + 3 Abort |
| 70 | + 4 Retry |
| 71 | + 5 Ignore |
| 72 | + 6 Yes |
| 73 | + 7 No |
| 74 | + .PARAMETER Message |
| 75 | + [string] The Message to display. |
| 76 | + .PARAMETER Title |
| 77 | + [string] The MessageBox Title. |
| 78 | + .PARAMETER TimeOut |
| 79 | + [int] The Timeout Value of the MessageBox in seconds. |
| 80 | + When the Timeout is reached the MessageBox closes and returns a value of -1. |
| 81 | + The Default is 0 - No Timeout. |
| 82 | + .PARAMETER ButtonSet |
| 83 | + [string] The Buttons to be Displayed in the MessageBox. |
| 84 | + |
| 85 | + Values: |
| 86 | + Value Buttons |
| 87 | + OK OK - This is the Default |
| 88 | + OC OK Cancel |
| 89 | + AIR Abort Ignore Retry |
| 90 | + YNC Yes No Cancel |
| 91 | + YN Yes No |
| 92 | + RC Retry Cancel |
| 93 | + .PARAMETER IconType |
| 94 | + [string] The Icon to be Displayed in the MessageBox. |
| 95 | + |
| 96 | + Values: |
| 97 | + None - This is the Default |
| 98 | + Critical |
| 99 | + Question |
| 100 | + Exclamation |
| 101 | + Information |
| 102 | + .EXAMPLE |
| 103 | + $RetVal = Show-PopUp -Message "Data Trucking Company" -Title "Popup Test" -TimeOut 5 -ButtonSet YNC -Icon Exclamation |
| 104 | + |
| 105 | + .NOTES |
| 106 | + FunctionName : Show-PopUp |
| 107 | + Created by : Data Trucking Company |
| 108 | + Date Coded : 06/25/2012 16:55:46 |
| 109 | + |
| 110 | + .LINK |
| 111 | + |
| 112 | + #> |
| 113 | + [CmdletBinding()][OutputType([int])]Param( |
| 114 | + [parameter(Mandatory=$true, ValueFromPipeLine=$true)][Alias("Msg")][string]$Message, |
| 115 | + [parameter(Mandatory=$false, ValueFromPipeLine=$false)][Alias("Ttl")][string]$Title = $null, |
| 116 | + [parameter(Mandatory=$false, ValueFromPipeLine=$false)][Alias("Duration")][int]$TimeOut = 0, |
| 117 | + [parameter(Mandatory=$false, ValueFromPipeLine=$false)][Alias("But","BS")][ValidateSet( "OK", "OC", "AIR", "YNC" , "YN" , "RC")][string]$ButtonSet = "OK", |
| 118 | + [parameter(Mandatory=$false, ValueFromPipeLine=$false)][Alias("ICO")][ValidateSet( "None", "Critical", "Question", "Exclamation" , "Information" )][string]$IconType = "None" |
| 119 | + ) |
| 120 | + |
| 121 | + $ButtonSets = "OK", "OC", "AIR", "YNC" , "YN" , "RC" |
| 122 | + $IconTypes = "None", "Critical", "Question", "Exclamation" , "Information" |
| 123 | + $IconVals = 0,16,32,48,64 |
| 124 | + if((Get-Host).Version.Major -ge 3){ |
| 125 | + $Button = $ButtonSets.IndexOf($ButtonSet) |
| 126 | + $Icon = $IconVals[$IconTypes.IndexOf($IconType)] |
| 127 | + } |
| 128 | + else{ |
| 129 | + $ButtonSets|ForEach-Object -Begin{$Button = 0;$idx=0} -Process{ if($_.Equals($ButtonSet)){$Button = $idx };$idx++ } |
| 130 | + $IconTypes |ForEach-Object -Begin{$Icon = 0;$idx=0} -Process{ if($_.Equals($IconType) ){$Icon = $IconVals[$idx]};$idx++ } |
| 131 | + } |
| 132 | + $objShell = New-Object -com "Wscript.Shell" |
| 133 | + $objShell.Popup($Message,$TimeOut,$Title,$Button+$Icon) |
| 134 | +} |
| 135 | + |
| 136 | +Function Get-ScheduledTasks{ |
| 137 | + [CmdletBinding()] |
| 138 | + Param ( |
| 139 | + [string]$computername |
| 140 | + ) |
| 141 | + $path = "\\" + $computername + "\c$\Windows\System32\Tasks" |
| 142 | + $tasks = Get-ChildItem -Path $path -File |
| 143 | + |
| 144 | + if ($tasks) |
| 145 | + { |
| 146 | + Write-Verbose -Message "I found $($tasks.count) tasks for $computername" |
| 147 | + } |
| 148 | + |
| 149 | + foreach ($item in $tasks) |
| 150 | + { |
| 151 | + $AbsolutePath = $path + "\" + $item.Name |
| 152 | + $task = [xml] (Get-Content $AbsolutePath) |
| 153 | + [STRING]$check = $task.Task.Principals.Principal.UserId |
| 154 | + |
| 155 | + if ($task.Task.Principals.Principal.UserId) |
| 156 | + { |
| 157 | + Write-Verbose -Message "Writing the log file with values for $computername" |
| 158 | + Add-content -path $logfilepath -Value "$computername,$item,$check" |
| 159 | + } |
| 160 | + |
| 161 | + } |
| 162 | + |
| 163 | +} |
| 164 | +##*=============================================== |
| 165 | +##* MAIN |
| 166 | +##*=============================================== |
| 167 | +$RunningTasks = Get-ScheduledTask -TaskName 'Monitor USB Boot Key - System Startup' |
| 168 | +If (!$SessionZero -and $RunningTasks.State -eq "Running"){ |
| 169 | + Stop-ScheduledTask -TaskName 'Monitor USB Boot Key - System Startup' |
| 170 | + taskkill /IM powershell.exe /FI "USERNAME eq SYSTEM" |
| 171 | +} |
| 172 | +Unregister-Event -SourceIdentifier volumeChange -ErrorAction SilentlyContinue |
| 173 | + |
| 174 | +Register-WmiEvent -Class win32_VolumeChangeEvent -SourceIdentifier volumeChange |
| 175 | +Write-Log ((get-date -format s) +" Beginning $ScriptName...") -writehost |
| 176 | +do{ |
| 177 | + $newEvent = Wait-Event -SourceIdentifier volumeChange |
| 178 | + $eventType = $newEvent.SourceEventArgs.NewEvent.EventType |
| 179 | + $eventTypeName = switch($eventType){ |
| 180 | + 1 {"Configuration changed"} |
| 181 | + 2 {"Device arrival"} |
| 182 | + 3 {"Device removal"} |
| 183 | + 4 {"docking"} |
| 184 | + } |
| 185 | + |
| 186 | + #Write-Log ((get-date -format s) +" Event detected = "+ $eventTypeName) -writehost |
| 187 | + if ($eventType -eq 2){ |
| 188 | + Write-Log ((get-date -format s) +" USB Key arrival event detected, getting USB details...") -writehost |
| 189 | + $driveLetter = $newEvent.SourceEventArgs.NewEvent.DriveName |
| 190 | + $driveLabel = ([wmi]"Win32_LogicalDisk='$driveLetter'").VolumeName |
| 191 | + Write-Log ((get-date -format s) +" Drive name = "+ $driveLetter) -writehost |
| 192 | + Write-Log ((get-date -format s) +" Drive label = "+ $driveLabel) -writehost |
| 193 | + # Execute process if drive matches specified condition(s) |
| 194 | + if ($driveLetter -eq 'I:' -and $driveLabel -eq 'BOOTKEY'){ |
| 195 | + Write-Log ((get-date -format s) +" Starting task in 3 seconds...") -writehost |
| 196 | + #Stop-Computer -computerName $env:COMPUTERNAME -force |
| 197 | + #start-process "Z:\sync.bat" |
| 198 | + } |
| 199 | + } ElseIf ($eventType -eq 3){ |
| 200 | + $driveLetter = $newEvent.SourceEventArgs.NewEvent.DriveName |
| 201 | + if ($driveLetter -eq 'I:'){ |
| 202 | + If ($SessionZero) { |
| 203 | + Write-Log ((get-date -format s) +" USB Key removal event detected, rebooting system...") -writehost |
| 204 | + Stop-Computer -computerName $env:COMPUTERNAME -Force |
| 205 | + } Else{ |
| 206 | + Write-Log ((get-date -format s) +" USB Key removal event detected, sending message...") -writehost |
| 207 | + $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" |
| 208 | + If ($result -eq 1){ # Accepted |
| 209 | + Write-Log ((get-date -format s) +" User accepted, Shutting down system...") -writehost |
| 210 | + Stop-Computer -computerName $env:COMPUTERNAME -force |
| 211 | + } ElseIf($result -eq 2){ # Cancelled |
| 212 | + Write-Log ((get-date -format s) +" User cancelled system shutdown...") -writehost |
| 213 | + } Else { #Let message continue |
| 214 | + Write-Log ((get-date -format s) +" Countdown ended, Shutting down system...") -writehost |
| 215 | + Stop-Computer -computerName $env:COMPUTERNAME -force |
| 216 | + } |
| 217 | + } |
| 218 | + } |
| 219 | + } |
| 220 | + Remove-Event -SourceIdentifier volumeChange |
| 221 | +} while (1 -eq 1) #Loop until next event |
| 222 | +Unregister-Event -SourceIdentifier volumeChange |
0 commit comments