-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScanMedia.ps1
394 lines (331 loc) · 15 KB
/
ScanMedia.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
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
###########################################################################################
################################# Media Check #############################################
###########################################################################################
<#
A validation check on video files to make sure there are no errors with the file.
Script use: Takes a PATH paramater to a folder for scanning media
.\ScanMedia.ps1 "C:\Media\Videos"
.\ScanMedia.ps1 -Path "C:\Media\Videos"
To scan media and attempt to Auto Repair files use -AutoRepair
.\ScanMedia.ps1 -AutoRepair "C:\Media\Videos"
To scan media and force a rescan of all files use -Rescan
.\ScanMedia.ps1 -Rescan "C:\Media\Videos"
To Change the crf Value used for encodes, change the following
.\ScanMedia.ps1 -crf 18
Version: 2.0
Changelog:
1.O - Initial Script creation
1.1 - Separated the Error Log files as some could be very big
1.2 - Incorporated an Auto-Repair function
1.3 - Added additional logging to CSV file for easy sorting
1.4 - Corrected issue with detecting old error logs
1.5 - Added check to make sure ffmpeg exists and change calling behaviour
1.6 - Implemented Join-Path to allow script to be run on non-Windows machines
1.7 - Enable file scanned history and added a -Rescan switch to force scanning
all files.
1.8 - Found an Error with Get-ChildItem and -path where it wouldn't scan top
level folders with [] in the name. Using -LiteralPath now.
1.9 - Fixed an issue with LiteralPath ignoring ignored extensions
1.9.1 Changed how the auto-repair function worked to duplicate plex's optimized
version settings to create an x264 file to better address file errors. It
can now correct more issues but not everything. Added a crf argument so
users can now select the quality of the repaired video files.
Enabled AutoDelete on repaired files only that have failed checks
1.9.2 Corrected issue with not getting the file size on a video file for a PASSED
video file. Modified the writing of the CSV into a function to remove commas
from file names
2.0 - Changed ScanPath to Path. Corrected double logging of repaired files. Bugfixes.
Moved log directories into a Log folder for better organization
Condensed the method of writing output
#>
#Requires -Version 3
Param (
# Auto-repair switch for the command line to have the script attempt to auto repair media if there is an issue
[switch]$AutoRepair,
# Auto-delete switch for the command line to have the script delete media that was not successfully repaired
[switch]$AutoDelete,
# Forces the script to ignore the Scan History File and forces a re-scan of all files in the path
[switch]$Rescan,
[Parameter(Mandatory=$true)][string]$Path,
[Int]$crf = 21
)
# Excluded file types. Add more extensions that you want the scan to ignore
$exclude = ".png",".jpg",".srt",".txt",".idx",".sub",".nfo",".db",".mp3"
$fullName = ""
$fileName = ""
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$scanHistory = Join-Path -path $scriptPath -childpath "ScanHistory.txt"
$Date = "$((Get-Date).ToString('yyyy-MM-dd'))"
$LogDir = Join-Path -path $scriptPath -childpath "Log"
$LogPath = Join-Path -path $LogDir -childpath "Log_$Date"
$ffmpegLog = Join-Path -path $LogPath -childpath "ffmpegerror.log"
$Logfile = Join-Path -path $LogPath -childpath "results.log"
$CSVfile = Join-Path -path $LogPath -childpath "results.csv"
$env:PATH = $env:PATH+";."
$OrigLength = $null
$RepairLength = $null
$ScriptVersion = 2.0
# Funtion to write lines to a log file
Function LogWrite
{
Param (
[String]$LogString,
[String]$Colour,
[switch]$Log)
If (!($log)) {
If ($Colour) {
Write-Host "$(Get-Date): $LogString" -ForegroundColor $Colour
} Else {
Write-Host "$(Get-Date): $LogString"
}
}
Add-content $LogFile -value "$(Get-Date): $LogString" -Force
}
# Function to attempt to repair a video object with ffmpeg.exe if -AutoRepair is selected
Function RepairFile
{
Param ([Object]$VideoFile)
# Get only the file name of the Video Object
$RepairFileName = $VideoFile.Name
# Get only the file name without the extension of the video object and remove the brackets
$RepairFileBaseName = $VideoFile.BaseName -replace '[][]',''
# Get all the variables to create the another file in the same directory with _repaired in the filename
$dir = $VideoFile.DirectoryName
$RepairVFileName = "$RepairFileBaseName" + "_repaired.mp4"
$RepairFullName = Join-Path -path $dir -ChildPath $RepairVFileName
LogWrite "Creating Repair File: $RepairFullName"
$RepairFileName = $RepairFileName -replace '[][]',''
$RepairFileName = $RepairFileName + "_repair.log"
$errorLog = Join-Path -path $LogPath -childpath $RepairFileName
# Attempt to repair the video file with ffmpeg
#ffmpeg.exe -i $VideoFile.FullName -c:v copy -c:a copy $RepairFullName 2> $errorLog
ffmpeg.exe -y -i $VideoFile.FullName -c:v libx264 -crf $crf -c:a aac -q:a 100 -strict -2 -movflags faststart -level 41 $RepairFullName 2> $errorLog
# Check to see if the repaired file still has errors
$RepairFile = Get-Item $RepairFullName
# Check the scan history file to see if the file has been scanned
$scanHistoryCheck = (Get-Content $scanHistory | Select-String -pattern $RepairFile.FullName -SimpleMatch)
If ($RepairFile.Name.Length -lt 1) {
LogWrite "There was an issue creating the repaired file with FFMPEG" -Colour "Red"
} ElseIf ($null -ne $scanHistoryCheck) {
CheckFile $RepairFile -AutoRepaired -RescanVideo
} Else {
CheckFile $RepairFile -AutoRepaired
}
}
# Function to check a supplied video object with ffmpeg.exe
Function CheckFile
{
Param (
[Object]$VideoFile,
[switch]$AutoRepaired,
[switch]$RescanVideo
)
# Get the full name of the Video Object with path included
$fullName = $VideoFile.FullName
# Get only the name of the video file
$fileName = $VideoFile.Name
# Save the length of the video file to make sure the repaired video file length matches original
If ($AutoRepaired)
{
$RepairLength = GetLength $VideoFile
} Else {
$OrigLength = GetLength $VideoFile
}
LogWrite "Scanning File: $fullName"
# Scan the file with FFMPEG
ffmpeg.exe -v error -i $fullName -f null - >$ffmpegLog 2>&1
# Check to see if the ffmpeg error log was empty
If ($Null -eq (Get-Content $ffmpegLog))
{
# Get information to log to the CSV file
$FileSize = "{0:N2}" -f (($VideoFile | Measure-Object -property length -sum ).sum / 1MB)
$Date = $((Get-Date).ToString('yyyy-MM-dd'))
If ($AutoRepaired)
{
# File is only repaired successfully if the video file length matches original
If (($RepairLength -eq $OrigLength) -and ($Null -ne $RepairLength))
{
LogWrite "File Repaired Successfully: $fullName" -Colour Green
Write-CSV -VidfileName $fileName -VidfilePath $fullName -TestResults "Passed" -Date $Date -VidFileSize $FileSize -VidLength $RepairLength
}
Else {
LogWrite "ERROR: Error Found in Repaired File. Video Length does not match Original: $fullName" -Colour "Red"
Write-CSV -VidfileName $fileName -VidfilePath $fullName -TestResults "Failed" -Date $Date -VidFileSize $FileSize -VidLength $RepairLength
If ($AutoDelete)
{
LogWrite "Deleting Repaired File: $fileName"
Remove-Item -Path $VideoFile
}
}
} else {
LogWrite "Scanned Successfully: $fullName" -Colour "Green"
Write-CSV -VidfileName $fileName -VidfilePath $fullName -TestResults "Passed" -Date $Date -VidFileSize $FileSize -VidLength $OrigLength
}
# If the video file is not a rescanned file, add it to the scan history
If (!$RescanVideo)
{
Add-content $scanHistory $fullName
}
# Check to see if the ffmpeg error log was not empty
} Elseif ($Null -ne (Get-Content $ffmpegLog)) {
# Get information to log to the CSV file
$FileSize = "{0:N2}" -f (($VideoFile | Measure-Object -property length -sum ).sum / 1MB)
$Date = $((Get-Date).ToString('yyyy-MM-dd'))
If ($AutoRepaired)
{
LogWrite "ERROR: Error found in Repaired File: $fullName" -Colour "Red"
Write-CSV -VidfileName $fileName -VidfilePath $fullName -TestResults "Failed" -Date $Date -VidFileSize $FileSize -VidLength $RepairLength
If ($AutoDelete)
{
LogWrite "Deleting Repaired File: $fileName"
Remove-Item -Path $VideoFile
}
} else {
LogWrite "ERROR: Error found: $fullName" -Colour "Red"
Write-CSV -VidfileName $fileName -VidfilePath $fullName -TestResults "Failed" -Date $Date -VidFileSize $FileSize -VidLength $OrigLength
}
# If the video file is not a rescanned file, add it to the scan history
If (!$RescanVideo)
{
Add-content $scanHistory $fullName
}
$fileName = $fileName -replace '[][]',''
$fileName = $fileName + "_error.log"
$errorLog = Join-Path -path $LogPath -ChildPath $fileName
If (Test-Path $errorLog)
{
LogWrite "Removing Error Log : $errorLog"
Remove-Item -Path $errorLog
}
try {
Rename-Item $ffmpegLog $errorLog
} catch
{
$ErrorMessage = $_.Exception.Message
LogWrite "ERROR: Failed to rename the ffmpeg log: $ErrorMessage" -Colour "Red"
LogWrite $ErrorMessage -Log
$errorLog = Join-Path -path $LogPath -childpath "GenericError.log"
Get-Content $ffmpegLog | Add-Content $errorLog
Remove-item $ffmpegLog
}
# Only contiune if the file is not already flaged as auto-repaired
if (!$AutoRepaired)
{
# Only continue if auto-repair is selected
if ($AutoRepair)
{
LogWrite "Attempting to Repair : $VideoFile"
# Supply the video object to the repair function
RepairFile $VideoFile
}
}
}
}
Function GetLength
{
Param ([Object]$VideoFile)
$LengthColumn = 27
$objShell = New-Object -ComObject Shell.Application
$objFolder = $objShell.Namespace($VideoFile.DirectoryName)
$objFile = $objFolder.ParseName($VideoFile.Name)
$VideoLength = $objFolder.GetDetailsOf($objFile, $LengthColumn)
return $VideoLength
}
Function Write-CSV
{
Param (
[String]$VidfileName,
[String]$VidfilePath,
[String]$TestResults,
[String]$Date,
[String]$VidFileSize,
[String]$VidLength
)
$VidfileName = $VidfileName -replace ',',''
$VidfilePath = $VidfilePath -replace ',',''
$CSVContent = "$VidfileName,$TestResults,$Date,$VidFileSize,$VidLength,$VidfilePath"
try {
Add-content $CSVfile -Value $CSVContent
}
catch {
$ErrorMessage = $_.Exception.Message
LogWrite "ERROR: Failed to log the result to the csv file $CSVfile" -Colour "Red"
LogWrite $ErrorMessage -Log
}
}
# Test to see if the log directory exists and create it if not
If(!(test-Path $LogDir))
{
New-Item -ItemType Directory -Force -Path $LogDir | Out-Null
}
If(!(test-Path $LogPath))
{
New-Item -ItemType Directory -Force -Path $LogPath | Out-Null
}
Clear-Host
LogWrite "Starting script $($MyInvocation.MyCommand.Name)" -Colour "Cyan"
# Test the CSV file path and create the CSV with the header line if it does not exist
If (!(test-Path $CSVfile))
{
Set-Content $CSVfile -Value "File Name,FFMPEG Test,Check Date,File Size (MB),Video Length,Location"
}
If (!(test-Path $scanHistory))
{
Set-Content $scanHistory -Value "This is a history of all scanned items. Please do not delete or modify this file."
LogWrite "Creating a history file: $scanHistory "
LogWrite "Please do not remove this file if you would like to keep a history of scanned items."
}
If ($AutoRepair)
{
LogWrite "Auto-Repair has been enabled" -Colour "Cyan"
}
If ($AutoDelete)
{
LogWrite "WARNING: Auto-Delete has been enabled. All repaired files that have errors will be automatically removed" -Colour "Yellow"
}
If ($Rescan)
{
LogWrite "Media Rescan has been enabled. All files will be scanned." -Colour "Cyan"
}
# Check to see if ffmpeg exists and if it is installed on the local machine and added to path
If ($null -eq (Get-Command "ffmpeg.exe" -ErrorAction SilentlyContinue))
{
LogWrite "ERROR: Unable to find ffmpeg.exe on the computer or in the local script directory" -Colour "Red"
LogWrite "Please download ffmpeg and place ffmpeg.exe in: $scriptPath" -Colour "Cyan"
LogWrite "Exiting Script" -Colour "Red"
Exit
}
# Check to make sure the path supplied to scan exists for the current user
If (!(Test-Path $Path)) {
LogWrite "ERROR: Unable to access the directory: $Path" -Colour "Red"
If (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
LogWrite "Running as administrator is not required and can cause issues accessing network folders that have been mapped. Please supply the direct share path I.E. \\SERVER\SHARE\PATH"
}
LogWrite "Exiting Script" -Colour "Red"
Exit
}
LogWrite "Script Version is $ScriptVersion"
LogWrite "###########################################################" -Log
LogWrite "Begining Scan on $Path"
LogWrite "###########################################################" -Log
# Get all the child items of the supplied directory and attempt to scan the files with the function CheckFile
Get-ChildItem -LiteralPath $Path -File -Recurse | Where-Object { $exclude -notcontains $_.Extension } | ForEach-Object {
# Check the scan history file to see if the file has been scanned
$scanHistoryCheck = (Get-Content $scanHistory | Select-String -pattern $_.FullName -SimpleMatch)
# If the file exists in the scan history and Rescan has not been enabled, skip
If (($scanHistoryCheck -ne $null) -and ($Rescan -eq $false))
{
LogWrite "Skipping scanned file:" $_.Name
}
# If the file exists in the scan history and Rescan has been enabled, scan the file
Elseif (($scanHistoryCheck -ne $null) -and ($Rescan -eq $true))
{
CheckFile $_ -RescanVideo
}
Else
{
CheckFile $_
}
}
LogWrite "Scan Log file: $Logfile"
LogWrite "Scan Complete."