-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkillaudio.ps1
More file actions
424 lines (371 loc) · 13.5 KB
/
killaudio.ps1
File metadata and controls
424 lines (371 loc) · 13.5 KB
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# Script: Monitor and Control NVIDIA Audio Devices
# Purpose: Automatically disable NVIDIA HD Audio devices in multi-monitor setups
# Usage: Can be run directly or via IRM from GitHub
# Author: David (C0deGeek)
# Repository: https://github.com/David-c0degeek/nvidia-audio-killer
#Region Configuration
$script:Config = @{
TaskName = "NvidiaAudioAutoDisable"
ScriptDir = "C:\DeviceAudioAutoDisable"
LogFile = "C:\DeviceAudioAutoDisable\AudioControl.log"
DevicePattern = "*NVIDIA High Definition Audio*"
RetryIntervalSeconds = 300 # 5 minutes
MaxRetries = 3
LongRetryIntervalMinutes = 30
LogCleanupDays = 7 # Cleanup logs older than 7 days
}
#EndRegion
#Region Validation
function Test-AdminAccess {
try {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal $identity
$adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator
if (-not $principal.IsInRole($adminRole)) {
Write-Log "This script requires administrator privileges" -Level Error
return $false
}
return $true
}
catch {
Write-Log "Error checking admin access: $_" -Level Error
return $false
}
}
function Test-SystemPermissions {
try {
# Test PnP cmdlet access
$null = Get-PnpDevice -Class AudioEndpoint -ErrorAction Stop
return $true
}
catch {
Write-Log "Error testing system permissions: $_" -Level Error
return $false
}
}
#EndRegion
#Region Logging
function Write-Log {
[CmdletBinding()]
param(
[string]$Message,
[ValidateSet('Info','Warning','Error','Success','Debug')]
[string]$Level = 'Info',
[switch]$NoConsole
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# Add emoji/symbol based on level
$symbol = switch ($Level) {
'Success' { '✓' }
'Warning' { '!' }
'Error' { '✕' }
'Debug' { '•' }
default { ' ' }
}
$logMessage = "[$timestamp] [$Level] $symbol $Message"
# Ensure log directory exists
$logDir = Split-Path $script:Config.LogFile -Parent
if (!(Test-Path $logDir)) {
New-Item -ItemType Directory -Path $logDir -Force | Out-Null
}
# Clean up old logs
Get-ChildItem -Path $logDir -Filter "*.log" |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$script:Config.LogCleanupDays) } |
Remove-Item -Force
Add-Content -Path $script:Config.LogFile -Value $logMessage
if (-not $NoConsole) {
$color = switch ($Level) {
'Success' { 'Green' }
'Warning' { 'Yellow' }
'Error' { 'Red' }
'Debug' { 'Gray' }
default { 'White' }
}
Write-Host $logMessage -ForegroundColor $color
}
}
#EndRegion
#Region Device Management
function Get-MonitorDetails {
param(
[Parameter(Mandatory)]
[string]$DeviceName
)
if ($DeviceName -match '(?<model>(LG ULTRAGEAR|27GL850)).*?(?<info>\(.*\))?') {
return @{
Model = $matches['model']
Info = if ($matches['info']) { $matches['info'] } else { '' }
}
}
return @{
Model = $DeviceName
Info = ''
}
}
function Disable-NvidiaAudioDevices {
[CmdletBinding()]
param(
[switch]$Force,
[switch]$Quiet
)
try {
if (-not $Quiet) {
Write-Log "Scanning for NVIDIA audio devices..." -Level Info
}
$devices = Get-PnpDevice | Where-Object {
$_.FriendlyName -like $script:Config.DevicePattern
}
$processedCount = 0
$monitorCount = @{}
foreach ($dev in $devices) {
$monitorInfo = Get-MonitorDetails -DeviceName $dev.FriendlyName
if (-not $monitorCount.ContainsKey($monitorInfo.Model)) {
$monitorCount[$monitorInfo.Model] = 0
}
$monitorCount[$monitorInfo.Model]++
$deviceDesc = "$($monitorInfo.Model) #$($monitorCount[$monitorInfo.Model])"
try {
# Try to disable with suppressed output
$null = Disable-PnpDevice -InstanceId $dev.InstanceId -Confirm:$false -ErrorAction SilentlyContinue
if (-not $Quiet) {
Write-Log "Device disabled: $deviceDesc" -Level Success
}
$processedCount++
}
catch {
$errorMsg = $_.Exception.Message
# Handle expected cases silently
if ($errorMsg -like "*Generic failure*" -or $errorMsg -like "*disabled*") {
$processedCount++
if (-not $Quiet) {
Write-Log "Device verified: $deviceDesc" -Level Success
}
}
else {
Write-Log "Failed to disable $deviceDesc`: $errorMsg" -Level Warning
}
}
}
if (-not $Quiet -and $processedCount -gt 0) {
Write-Log "Successfully processed $processedCount NVIDIA audio device(s)" -Level Success
foreach ($monitor in $monitorCount.GetEnumerator()) {
Write-Log "- $($monitor.Key): $($monitor.Value) audio device(s)" -Level Debug
}
}
return $true
}
catch {
Write-Log "Critical error in device management: $_" -Level Error
return $false
}
}
#EndRegion
#Region Monitor Script Generation
function New-MonitorScript {
$monitorScriptPath = Join-Path $script:Config.ScriptDir "DeviceMonitor.ps1"
$monitorContent = @'
param(
[Parameter(Mandatory)]
[string]$LogFile,
[Parameter(Mandatory)]
[string]$DevicePattern,
[int]$RetryIntervalSeconds = 300,
[int]$MaxRetries = 3,
[int]$LongRetryIntervalMinutes = 30
)
$script:Config = @{
LogFile = $LogFile
DevicePattern = $DevicePattern
}
# Import required functions (copied from main script)
${function:Write-Log} = ${function:Write-Log}
${function:Get-MonitorDetails} = ${function:Get-MonitorDetails}
${function:Disable-NvidiaAudioDevices} = ${function:Disable-NvidiaAudioDevices}
function Register-DeviceMonitor {
param([int]$RetryCount = 0)
try {
# Define device management action
$action = {
Write-Log "Device change detected, running check..." -Level Debug -NoConsole
Disable-NvidiaAudioDevices -Quiet
}
# Register for specific device change events
$query = @"
SELECT * FROM Win32_DeviceChangeEvent
WHERE EventType = 2
AND TargetInstance ISA 'Win32_PnPEntity'
"@
$null = Register-WmiEvent -Query $query -Action $action -ErrorAction Stop
Write-Log "Device monitoring initialized successfully" -Level Success
return $true
}
catch {
Write-Log "Error registering device monitor (Attempt $($RetryCount + 1)): $_" -Level Error
if ($RetryCount -lt $MaxRetries) {
Write-Log "Retrying in $RetryIntervalSeconds seconds..." -Level Info
Start-Sleep -Seconds $RetryIntervalSeconds
return Register-DeviceMonitor -RetryCount ($RetryCount + 1)
}
return $false
}
}
# Initial device check
Write-Log "Performing initial device check..." -Level Info
Disable-NvidiaAudioDevices
# Main monitoring loop
while ($true) {
if (-not (Get-Variable -Name EventSubscriber -ErrorAction SilentlyContinue)) {
Write-Log "Starting device monitor..." -Level Info
if (Register-DeviceMonitor) {
Write-Log "Monitor active and watching for device changes" -Level Success
}
else {
Write-Log "Failed to initialize monitor, will retry in $LongRetryIntervalMinutes minutes" -Level Warning
Start-Sleep -Seconds ($LongRetryIntervalMinutes * 60)
continue
}
}
# Periodic check
Start-Sleep -Seconds $RetryIntervalSeconds
Disable-NvidiaAudioDevices -Quiet
}
'@
if (!(Test-Path $script:Config.ScriptDir)) {
New-Item -ItemType Directory -Path $script:Config.ScriptDir -Force | Out-Null
}
Set-Content -Path $monitorScriptPath -Value $monitorContent -Encoding UTF8
return $monitorScriptPath
}
#EndRegion
#Region Service Management
function Install-AudioControl {
try {
Write-Log "Starting installation..." -Level Info
# Verify permissions
if (-not (Test-AdminAccess)) {
throw "Administrator privileges required"
}
if (-not (Test-SystemPermissions)) {
throw "Insufficient system permissions to manage devices"
}
# Create monitor script
$monitorScript = New-MonitorScript
Write-Log "Monitor script created at: $monitorScript" -Level Success
# Build argument list
$scriptArguments = @(
"-WindowStyle Hidden"
"-ExecutionPolicy Bypass"
"-File `"$monitorScript`""
"-LogFile `"$($script:Config.LogFile)`""
"-DevicePattern `"$($script:Config.DevicePattern)`""
"-RetryIntervalSeconds $($script:Config.RetryIntervalSeconds)"
"-MaxRetries $($script:Config.MaxRetries)"
"-LongRetryIntervalMinutes $($script:Config.LongRetryIntervalMinutes)"
) -join ' '
# Create scheduled task
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $scriptArguments
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -RunLevel Highest -LogonType ServiceAccount
$settings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)
Register-ScheduledTask -TaskName $script:Config.TaskName `
-Action $action `
-Trigger $trigger `
-Principal $principal `
-Settings $settings `
-Description "Automatically disable NVIDIA HD Audio devices" `
-Force
Write-Log "Installation completed successfully" -Level Success
# Immediate first run
Disable-NvidiaAudioDevices -Force
}
catch {
Write-Log "Installation failed: $_" -Level Error
throw
}
}
function Uninstall-AudioControl {
try {
Write-Log "Starting uninstallation..." -Level Info
# Remove scheduled task
if (Get-ScheduledTask -TaskName $script:Config.TaskName -ErrorAction SilentlyContinue) {
Unregister-ScheduledTask -TaskName $script:Config.TaskName -Confirm:$false
Write-Log "Scheduled task removed" -Level Success
}
# Clean up script directory
if (Test-Path $script:Config.ScriptDir) {
Remove-Item $script:Config.ScriptDir -Recurse -Force
Write-Log "Script directory removed" -Level Success
}
Write-Log "Uninstallation completed successfully" -Level Success
}
catch {
Write-Log "Uninstallation failed: $_" -Level Error
throw
}
}
#EndRegion
#Region Main Menu
function Show-Menu {
Write-Host "`nNVIDIA Audio Control Menu" -ForegroundColor Cyan
Write-Host "1) Install and enable audio control"
Write-Host "2) Uninstall and disable audio control"
Write-Host "3) Check current status"
Write-Host "4) View logs"
Write-Host "5) Force immediate device check"
Write-Host "Q) Quit"
$choice = Read-Host "`nEnter your choice"
switch ($choice) {
'1' {
Install-AudioControl
}
'2' {
Uninstall-AudioControl
}
'3' {
$task = Get-ScheduledTask -TaskName $script:Config.TaskName -ErrorAction SilentlyContinue
if ($task) {
Write-Host "`nStatus: Installed and $($task.State)" -ForegroundColor Green
Write-Host "Last Run Time: $($task.LastRunTime)"
Write-Host "Next Run Time: $($task.NextRunTime)"
# Check current devices
$devices = Get-PnpDevice | Where-Object {
$_.FriendlyName -like $script:Config.DevicePattern
}
if ($devices) {
Write-Host "`nCurrent NVIDIA audio devices:" -ForegroundColor Cyan
$devices | Format-Table FriendlyName, Status -AutoSize
}
} else {
Write-Host "`nStatus: Not installed" -ForegroundColor Yellow
}
}
'4' {
if (Test-Path $script:Config.LogFile) {
Get-Content $script:Config.LogFile | Select-Object -Last 20
} else {
Write-Host "No logs found"
}
}
'5' {
Write-Host "Performing immediate device check..."
Disable-NvidiaAudioDevices -Force
}
'Q' {
return $false
}
default {
Write-Host "Invalid choice" -ForegroundColor Red
}
}
return $true
}
# Main execution
if ($MyInvocation.InvocationName -eq "&") {
# Script is being run via IRM
Install-AudioControl
} else {
# Interactive mode
do {
$continue = Show-Menu
} while ($continue)
}