我创建了一个PowerShell脚本来使用YouTube-DL下载视频。成功下载视频后,我想复制其.info.json
文件,然后将其附加到我用作数据库的脚本文件中。YouTube-DL提供--exec
参数,该参数允许您在成功下载视频时运行命令。这是我的脚本:
Write-Host "Checking for updates to youtube-dl . . . "
.youtube-dl.exe -U
Write-Host "Searching for and downloading videos . . . "
$PSDefaultParameterValues['Out-File:Encoding'] = 'UTF8'
if (![System.IO.File]::Exists('.database.js')) {
Set-Content -Path .database.js -Value "const database = [
]"
}
$stopWatch = [system.diagnostics.stopwatch]::startNew()
.youtube-dl.exe --config-location config.txt --write-info-json --exec "Write-MetadataToDatabase {}" # Call the Write-MetadataToDatabase function, passing the location of the video .info.json file as {}
$elapsed = $stopWatch.Elapsed.ToString("hh:mm:ss")
Write-Host "Finished downloading. Took $elapsed."
Read-Host -Prompt "Done, press Enter to exit"
function Write-MetadataToDatabase {
Param($Path)
$content = [System.IO.File]::ReadAllText($Path, [System.Text.Encoding]::UTF8) | ConvertFrom-Json
$content.PSObject.Properties.Remove('formats')
$content = $content | ConvertTo-Json -compress
$stream = [IO.File]::OpenWrite('.database.js')
$stream.SetLength($stream.Length - 4)
$stream.Close()
$stream.Dispose()
$content + ",
]" | Add-Content .database.js -Encoding UTF8
$i++
Write-Host "Appended video metadata to database file"
}
成功下载视频后,如何运行我的功能,通过视频的.info.json
文件的位置?
编辑我已经想出了如何获取.info.json
文件的位置。将{}作为--exec
参数传递,返回视频的位置,该位置与元数据文件相同。我仍然不知道如何成功调用我的功能。
我无法让--Exec
参数工作,但是这是一种可以使您开始的方法。
$files = "https://www.youtube.com/watch?v=avWtg18HMbQ"
forEach ($file in $files){
& '.youtube-dl.exe' "$($file) --write-info-json -i -f bestvideo+bestaudio/best"
$elapsed = $stopWatch.Elapsed.ToString("hh:mm:ss")
Write-Host "Finished downloading. Took $elapsed."
#find most recent file
$thisJSONFile = Get-ChildItem *.json | Sort-Object -Descending Created | Select-Object -First 1 | Get-Content | ConvertFrom-Json
Write-Output "The most recent file was $($thisJSONFile._filename) which had $($thisJSONFile.view_count) views"
#do other things with properties of $thisJSONFile here
}
将提供此输出
The most recent file was [No Damage_Ichimonji] SEVEN ASHINA SPEARS Shikibu Toshikatsu Yamauchi Mini-Boss Fight _ Sekiro-DdMUG3PvWII.mp4 which had 16 views
您可以将自己的逻辑添加到脚本块的末尾,以对下载的.json文件进行任何您想做的事情,我希望这会有所帮助。