Skip to content

Instantly share code, notes, and snippets.

@ReenigneArcher
Forked from Desani/ScanMedia.md
Last active December 12, 2020 19:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ReenigneArcher/a384a4229ff81f4f64d8a5a5d2509e92 to your computer and use it in GitHub Desktop.
Save ReenigneArcher/a384a4229ff81f4f64d8a5a5d2509e92 to your computer and use it in GitHub Desktop.
Added Hardware accelarated encoding switch and ability to specify repaired file extension

Hi /r/PleX,

I am sure like many of you, I have gathered a large number of media files over the years to add to my Plex collection. I have constantly been looking for a solution to find out if I had corrupted media in my library and I was never happy with just waiting till a user reported that a file could not be played properly.

I recently learned after looking into it again that ffmpeg.exe could be used to scan media and report back and errors while reading the file. I decided to whip up a powershell script that would supply ffmpeg all the video files in a directory and have it scan that file for errors. The script will log the output from ffmpeg, if there is any, and will record if a file has passed or failed a file scan. A history of the script output is saved to a log file and also each file scanned is added to a CSV file for easy sorting after a library has scanned.

There is a command line argument to have the script auto-repair the file, but if I remember correctly from reading online, ffmpeg can only repair container errors, so I have not had success at having ffmpeg auto-repairing most files. If any of you have a better idea on how this could be accomplished I would like some suggestions, even if it is another program that can accept command line arguments.

There is a command line argument to have the script auto-delete. This has not been implemented yet. I was going to have the script delete the file with errors if the auto-repair was selected and the repair was successful.

Script use: Download and save the script as a .ps1 file on your windows computer. Download the ffmpeg windows binary and place the ffmpeg.exe in the same folder as the downloaded script.

Note: in order to run powershell scripts you download you might have to type the following in an elevated powershell window to run the script:

Set-ExecutionPolicy Unrestricted

Once you are done running the script you can set the Execution policy back with:

Set-ExecutionPolicy Restricted

.PARAMETER Path Calling Syntax: -Path "C:\Media\Videos" or -Path "\SEVERVERSHARE\Media\Videos"

Parameter Description: This is a required parameter. This is the location that the script will begin recursivly scanning with FFMPEG. If running this script as administrator, you typically want to provide the full network path instead of a drive letter.

.PARAMETER RepairedExt Calling Syntax: -RepairedExt "mkv"

Parameter Description: This is an optional parameter. This is the repaired file extension. If not supplied will default to mp4.

.PARAMETER AutoRepair Calling Syntax: -AutoRepair

Parameter Description: When supplied, the script will automatticly attempt to repair any file that is found to have issues. Only a certain number of issues will be able to be corrected with method and it will not be possible to repair all files. After a video is repaired, it is then scanned to check to make sure the repair was successful and verify's that the runtime matches that of the original file.

.PARAMETER Rescan Calling Syntax: -Rescan

Parameter Description: When supplied, forces the script to ignore the Scan History File and forces a re-scan of all files in the path supplied.

.PARAMETER CRF Calling Syntax: -CRF 25

Parameter Description: Stands for Constant Rate Factor, can be within the range of 0 - 51, where 0 is lossless and 51 is the worst quality possible. 21 is the default value for this script. A lower value generally leads to higher quality, and a subjectively sane range is 17–28. Consider 17 or 18 to be visually lossless or nearly so; it should look the same or nearly the same as the input but it isn't technically lossless. The range is exponential, so increasing the CRF value +6 results in roughly half the bitrate / file size, while -6 leads to roughly twice the bitrate.

.PARAMETER LimitCPU Calling Syntax: -LimitCPU

Parameter Description: When supplied, the script will attempt to run FFMPEG with half of the availible cores assigned to the current system. If 4 cores are availible, FFMPEG will utilize 2. If 1 core is availible to the system, this parameter will have no affect. Scan and repair time will increase with this parameter.

.PARAMETER UseGPU Calling Syntax: -UseGPU

Parameter Description: When supplied, the script will run FFMPEG with h264_nvenc encoding. FFMPEG must be compiled per the instructions in the readme.

.PARAMETER RemoveAll Calling Syntax: -RemoveAll

Parameter Description: When supplied, will DELETE all of the files that are found to have errors and is not dependant of if they are able to be successfully repaird. It is recommended to only run this command if a backup is in place for the media being scanned. If -IAcceptResponsibility is not supplied at run time, the script will prompt the user to type IACCEPT durring runtime.

.PARAMETER RemoveRepaired Calling Syntax: -RemoveRepaired

Parameter Description: When supplied, the script will DELETE all of the repaired files that did not scan as successfully repaired.

.PARAMETER RemoveOriginal Calling Syntax: -RemoveOriginal

Parameter Description: When supplied, the script will DELETE the orignal video file if it was repaired successfully. It will then overwrite the original file name with the name of the successfully repaired file. It is recommended to only run this command if a backup is in place for the media being scanned. If -IAcceptResponsibility is not supplied at run time, the script will prompt the user to type IACCEPT durring runtime.

.PARAMETER IAcceptResponsibility Calling Syntax: -IAcceptResponsibility

Parameter Description: When supplied, the user accepts responsibility when suppling paramaters that will potentially delete orignal files. This should only be used when you understand the risks involved.

.EXAMPLE .\ScanMedia.ps1 "C:\Media\Videos" .\ScanMedia.ps1 -Path "C:\Media\Videos" Both recursively scans the folder C:\Media\Videos for errors

.\ScanMedia.ps1 -AutoRepair "C:\Media\Videos" To scan media and attempt to Auto Repair files use -AutoRepair

.\ScanMedia.ps1 -Rescan "C:\Media\Videos" To scan media and force a rescan of all files use -Rescan

.\ScanMedia.ps1 -CRF 18 -Path "C:\Media\Videos" -AutoRepair To Change the CRF Value used for encodes, change the following

.\ScanMedia.ps1 -Path "C:\Media\Videos" -LimitCPU -AutoRepair -RemoveOriginal -RemoveRepaired Scans the path C:\Media\Videos with lower CPU usage and attempts to repair the files that are found to have an issue. The script will delete repaired files that don't repair properly and it will delete the original files of successfully repaired files.

You are able to take advantange of encoding with GPU Acceleration on linux and windows if you compile the ffmpeg binaries to support nvec. Please refer to this link to see if your GPU is supported: https://developer.nvidia.com/ffmpeg 1: Compile FFMPEG using this cross compile script: https://github.com/rdp/ffmpeg-windows-build-helpers 2: Verify that the new NVENC encoders are now included by using the following commands against the the compiled FFMPEG binaries: ffmpeg -encoders ffmpeg -decoders 3: Enable the -UseGPU paramater

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
    2.1 - Correct issue with logging skipped files
    2.2 - Added the ability to Limit CPU usage to half the cores detected on the machine.
            Added the abiltity to remove original files and all files that are found with errors.
    2.3 - Corrected issue with testing a path of a file containing "[]" characters.
    2.4 - Added the ability to use GPU encoding with a parameter instead of modifying the script.
            Added the ability to specify the repaired file extension.
###########################################################################################
################################# Media Check #############################################
###########################################################################################
#Requires -Version 3
<#
.SYNOPSIS
A validation check on video files to make sure there are no errors with the file. The script is able to auto-repair some encoding issues with video files.
THe script will keep track of all scanned files that are not deleted so that it can be setup to re-scan the same directory but only newly added files will be scanned.
Script use: Takes a PATH paramater to a folder for scanning media
.PARAMETER Path
Calling Syntax: -Path "C:\Media\Videos" or -Path "\\SEVERVERSHARE\Media\Videos"
Parameter Description: This is a required parameter. This is the location that the script will begin recursivly scanning with FFMPEG.
If running this script as administrator, you typically want to provide the full network path instead of a drive letter.
.PARAMETER RepairedExt
Calling Syntax: -RepairedExt "mkv"
Parameter Description: This is an optional parameter. This is the repaired file extension. If not supplied will default to mp4.
.PARAMETER AutoRepair
Calling Syntax: -AutoRepair
Parameter Description: When supplied, the script will automatticly attempt to repair any file that is found to have issues.
Only a certain number of issues will be able to be corrected with method and it will not be possible to repair all files. After a video is repaired,
it is then scanned to check to make sure the repair was successful and verify's that the runtime matches that of the original file.
.PARAMETER Rescan
Calling Syntax: -Rescan
Parameter Description: When supplied, forces the script to ignore the Scan History File and forces a re-scan of all files in the path supplied.
.PARAMETER CRF
Calling Syntax: -CRF 25
Parameter Description: Stands for Constant Rate Factor, can be within the range of 0 - 51, where 0 is lossless and 51 is the worst quality possible. 21 is the default value for this script.
A lower value generally leads to higher quality, and a subjectively sane range is 17–28. Consider 17 or 18 to be visually lossless or nearly so; it should look the same or nearly
the same as the input but it isn't technically lossless.
The range is exponential, so increasing the CRF value +6 results in roughly half the bitrate / file size, while -6 leads to roughly twice the bitrate.
.PARAMETER LimitCPU
Calling Syntax: -LimitCPU
Parameter Description: When supplied, the script will attempt to run FFMPEG with half of the availible cores assigned to the current system. If 4 cores are availible, FFMPEG will utilize 2.
If 1 core is availible to the system, this parameter will have no affect. Scan and repair time will increase with this parameter.
.PARAMETER UseGPU
Calling Syntax: -UseGPU
Parameter Description: When supplied, the script will run FFMPEG with h264_nvenc encoding. FFMPEG must be compiled per the instructions in the readme.
.PARAMETER RemoveAll
Calling Syntax: -RemoveAll
Parameter Description: When supplied, will DELETE all of the files that are found to have errors and is not dependant of if they are able to be successfully repaird.
It is recommended to only run this command if a backup is in place for the media being scanned.
If -IAcceptResponsibility is not supplied at run time, the script will prompt the user to type IACCEPT durring runtime.
.PARAMETER RemoveRepaired
Calling Syntax: -RemoveRepaired
Parameter Description: When supplied, the script will DELETE all of the repaired files that did not scan as successfully repaired.
.PARAMETER RemoveOriginal
Calling Syntax: -RemoveOriginal
Parameter Description: When supplied, the script will DELETE the orignal video file if it was repaired successfully. It will then overwrite the original file name with the name of the successfully repaired file.
It is recommended to only run this command if a backup is in place for the media being scanned.
If -IAcceptResponsibility is not supplied at run time, the script will prompt the user to type IACCEPT durring runtime.
.PARAMETER IAcceptResponsibility
Calling Syntax: -IAcceptResponsibility
Parameter Description: When supplied, the user accepts responsibility when suppling paramaters that will potentially delete orignal files. This should only be used when you understand the risks involved.
.EXAMPLE
.\ScanMedia.ps1 "C:\Media\Videos"
.\ScanMedia.ps1 -Path "C:\Media\Videos"
Both recursively scans the folder C:\Media\Videos for errors
.\ScanMedia.ps1 -AutoRepair "C:\Media\Videos"
To scan media and attempt to Auto Repair files use -AutoRepair
.\ScanMedia.ps1 -Rescan "C:\Media\Videos"
To scan media and force a rescan of all files use -Rescan
.\ScanMedia.ps1 -CRF 18 -Path "C:\Media\Videos" -AutoRepair
To Change the CRF Value used for encodes, change the following
.\ScanMedia.ps1 -Path "C:\Media\Videos" -LimitCPU -AutoRepair -RemoveOriginal -RemoveRepaired
Scans the path C:\Media\Videos with lower CPU usage and attempts to repair the files that are found to have an issue.
The script will delete repaired files that don't repair properly and it will delete the original files of successfully repaired files.
.NOTES
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
2.1 - Correct issue with logging skipped files
2.2 - Added the ability to Limit CPU usage to half the cores detected on the machine.
Added the abiltity to remove original files and all files that are found with errors.
2.3 - Corrected issue with testing a path of a file containing "[]" characters.
2.4 - Added the ability to use GPU encoding with a parameter instead of modifying the script.
Added the ability to specify the repaired file extension.
You are able to take advantange of encoding with GPU Acceleration on linux and windows if you compile the ffmpeg binaries to support nvec.
This has not been tested with this script and is not supported but it should still be possible.
Please refer to this link to see if your GPU is supported: https://developer.nvidia.com/ffmpeg
1: Compile FFMPEG using this cross compile script:
https://github.com/rdp/ffmpeg-windows-build-helpers
2: Verify that the new NVENC encoders are now included by using the following commands against the the compiled FFMPEG binaries:
ffmpeg -encoders
ffmpeg -decoders
3: Enable the -UseGPU paramater
#>
Param (
[Parameter(Mandatory=$true)][string]$Path,
[Parameter(Mandatory=$false)][string]$RepairedExt,
[switch]$AutoRepair,
[switch]$Rescan,
[Int]$CRF = 21,
[switch]$LimitCPU,
[switch]$UseGPU,
[switch]$RemoveAll,
[switch]$RemoveRepaired,
[switch]$RemoveOriginal,
[switch]$IAcceptResponsibility
)
# 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+";."
$global:OrigLength = $null
$global:RepairLength = $null
$global:RepairedFile = $null
$global:OriginalFile = $null
$global:OrignalRemoved = $false
$global:CPULimt = 1
$ScriptVersion = 2.4
# 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 the repaired file extension
If ("" -eq $RepairedExt) {
$RepairedExt = "mp4"
}
# Get all the variables to create the another file in the same directory with _repaired in the filename
$dir = $VideoFile.DirectoryName
$RepairVFileName = "$RepairFileBaseName" + "_repaired." + $RepairedExt
$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
If ($UseGPU) {
ffmpeg.exe -y -i $VideoFile.FullName -c:v h264_nvenc -crf $CRF -c:a aac -q:a 100 -strict -2 -movflags faststart -level 41 $RepairFullName 2> $errorLog
}
ElseIf ($LimitCPU) {
ffmpeg.exe -y -i $VideoFile.FullName -c:v libx264 -crf $CRF -c:a aac -q:a 100 -strict -2 -threads $global:CPULimt -movflags faststart -level 41 $RepairFullName 2> $errorLog
} Else {
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
)
# If the file is a new file being check, clear out the variables
If (!($AutoRepaired))
{
$global:RepairLength = $null
$global:RepairedFile = $null
$global:OrigLength = $null
$global:OriginalFile = $null
}
# Reset the Deleted value
$Deleted = $false
# 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 and object of the video file to make sure the repaired video file length matches original
If ($AutoRepaired)
{
$global:RepairLength = GetLength $VideoFile
$global:RepairedFile = $VideoFile
} Else {
$global:OrigLength = GetLength $VideoFile
$global:OriginalFile = $VideoFile
}
LogWrite "Scanning File: $fullName"
# Scan the file with FFMPEG
If ($LimitCPU) {
ffmpeg.exe -v error -i $fullName -f null -threads $global:CPULimt - >$ffmpegLog 2>&1
} Else {
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 the file is an Auto-Repaired File
If ($AutoRepaired)
{
# File is only repaired successfully if the video file length matches original
If (($global:RepairLength -eq $global:OrigLength) -and ($Null -ne $global:RepairLength))
{
LogWrite "File Repaired Successfully: $fullName" -Colour "Green"
Write-CSV -VidfileName $fileName -VidfilePath $fullName -TestResults "Passed" -Date $Date -VidFileSize $FileSize -VidLength $RepairLength
If ($RemoveOriginal -or $RemoveAll) {
# Remove the origial file and rename the repair file
LogWrite "Deleting the original file: $($global:OriginalFile.Name)" -Colour "Yellow"
Try {
Get-ChildItem -LiteralPath $global:OriginalFile.FullName -File | Remove-Item -Force -ErrorAction Stop
LogWrite "Renaming Repaired file to Orignal File"
$NewFileName = $global:OriginalFile.BaseName + $global:RepairedFile.Extension
Rename-Item -Path $global:RepairedFile.FullName -NewName $NewFileName -ErrorAction Stop
$Deleted = $true
$global:OrignalRemoved = $true
} Catch {
$ErrorMessage = $_.Exception.Message
LogWrite "Error: $ErrorMessage" -Colour "Red"
}
}
}
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 ($RemoveAll -or $RemoveRepaired)
{
LogWrite "Deleting Repaired File: $fileName" -Colour "Yellow"
Get-ChildItem -LiteralPath $VideoFile.FullName -File | Remove-Item -Force -ErrorAction Stop
$Deleted = $true
}
}
# If the file is not an Auto-Repaired file
} 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)
{
#If the video has been deleted, do not log the file name in scanHistory file for scanning again at a later time.
If (!($Deleted)) {
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 ($RemoveAll -or $RemoveRepaired)
{
LogWrite "Deleting Repaired File: $fileName" -Colour "Yellow"
Get-ChildItem -LiteralPath $VideoFile.FullName -File | Remove-Item -Force -ErrorAction Stop
$Deleted = $true
}
} else {
LogWrite "ERROR: Error found: $fullName" -Colour "Red"
Write-CSV -VidfileName $fileName -VidfilePath $fullName -TestResults "Failed" -Date $Date -VidFileSize $FileSize -VidLength $OrigLength
}
$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
}
}
If ($RemoveAll) {
# Remove the original file even if the repair was not successful
If (!($AutoRepaired)) {
If ($global:OrignalRemoved -eq $false){
LogWrite "Deleting the original file: $($VideoFile.Name)" -Colour "Yellow"
Get-ChildItem -LiteralPath $VideoFile.FullName -File | Remove-Item -Force -ErrorAction Stop
$Deleted = $true
}
$global:OrignalRemoved = $false
}
}
# If the video file is not a rescanned file, add it to the scan history
If (!$RescanVideo)
{
#If the video has been deleted, do not log the file name in scanHistory file for scanning again at a later time.
If (!($Deleted)) {
# Get the updated Original file name if the file was repaired
$NewFileName = Join-Path -Path $global:OriginalFile.DirectoryName -ChildPath $global:OriginalFile.BaseName
$NewFileName = $NewFileName + $global:RepairedFile.Extension
Try {
$NewFileObject = Get-ChildItem -LiteralPath $NewFileName -File -ErrorAction Stop
} Catch {
# If no matches are found, do nothing
}
If ($NewFileObject) {
Add-Content $scanHistory $NewFileObject.FullName
} Else {
Add-Content $scanHistory $fullName
}
}
}
}
}
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
If ($RemoveAll -or $RemoveOriginal) {
If (!($IAcceptResponsibility)) {
$Acceptance = ""
LogWrite "************************* WARNING *******************************" -Colour "Red"
LogWrite "The commands supplied have the ability to delete original files" -Colour "Yellow"
LogWrite "A backup is highly recommended when supplying these commands" -Colour "Yellow"
LogWrite "Please type the following confirm you understand: IACCEPT" -Colour "Yellow"
LogWrite "************************* WARNING *******************************" -Colour "Red"
while ($Acceptance -ne "IACCEPT") {
Write-Host "Please Type the above command: " -ForegroundColor Magenta -NoNewline
$Acceptance = Read-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 ($Rescan)
{
LogWrite "Media Rescan has been enabled. All files will be scanned." -Colour "Cyan"
}
If ($RemoveRepaired)
{
LogWrite "WARNING: Auto-Delete has been enabled for repaired files. All repaired files that have errors will be automatically removed" -Colour "Yellow"
}
If ($RemoveAll)
{
LogWrite "WARNING: Auto-Delete has been enabled for all files. All files that have errors will be automatically removed" -Colour "Yellow"
}
If ($RemoveOriginal)
{
LogWrite "WARNING: Auto-Delete has been enabled for original files. All original files that have errors will be automatically removed after a repair has completed successfully" -Colour "Yellow"
}
If ($IAcceptResponsibility) {
LogWrite "You have acknowledged that original files will potentially be removed when using RemoveAll or RemoveOriginal and supplying -IAcceptResponsibility" -Colour "Magenta"
}
If ($LimitCPU) {
LogWrite "Determining the number of CPUs to utilize for lower CPU usage." -Colour "Cyan"
$global:CPULimt = (Get-CimInstance Win32_ComputerSystem).NumberOfLogicalProcessors / 2
If ($global:CPULimt -lt 1) {
$global:CPULimt = 1
}
LogWrite "Limiting the CPU usage for FFMPEG to $global:CPULimt core(s)"
}
If ($UseGPU) {
LogWrite "Hardware accelaration has been enabled" -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 -LiteralPath $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."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment