LoginSignup
4
6

More than 5 years have passed since last update.

Youtube_dlを使って特定のプレイリストの動画を自動保存するPowerShellコード

Posted at

前提条件としてYoutubeDataApiのキーが必要。ググって各自取るとよい。pythonのyoutube-dlも必要

使い方

youtube-dl.ps1
& youtube-dl.ps1 -playlistId "PLwDaeL3aOb-x8wxSdbJvG0zOPGYLGz0tD"  -downloadLog list.txt -filePrefix "red-"

こんな感じ。playListIdは必須パラメーター。それ以外は任意。ただし、downloadLogのパラメーターを付けないと毎回全ての動画をDLする事になるから注意。
-filePrefixはその通りファイル名の頭につける。その辺は各自カスタマイズしてね

動作として、YoutubeAPIを使って指定のプレイリストの動画一覧を取得する→downloadLogのファイルを読み込んでファイルIDがあったらスキップ→ファイルIDが無い時はそれをダウンロード。って感じ。これをcronと組み合わせればとても美味しい

# utf16です
Param(
    [Parameter(mandatory)][string]$playlistId = "" ,
    [string]$downloadLog = "" ,
    [string]$filePrefix="" 
)
$script:apiKey="";#各自よろしく

function Main{
    $vids = getDownloadVideoIdList
    $vids | foreach{
    #   "line=[$_] "+$_.getType()
    }
    getAllSnippet $playlistId  | foreach {
        $videoId=$_.resourceId | foreach videoId
        if ( $videoId -eq $null ){
            return
        }
        if ( $vids -contains $videoId){
            return
        }
        $argument = "-o `"${filePrefix}%(title)s[%(display_id)s].%(ext)s`" --no-check-certificate --no-mtime `"${videoId}`""
        $r=Start-Process -FilePath "youtube-dl" -ArgumentList $argument -Wait -NoNewWindow  -PassThru
        if ( $r.exitCode -eq 0 -and $downloadLog -ne "" ){
            $videoId >> $downloadLog
        }
        if($r.exitCode -ne 0){
        }
    }
}
function getAllSnippet($psID){
    while($true){
        if( $nextToken -eq "" ){
            $url="https://content.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${playlistId}&key=${apiKey}"
        }else{
            $url="https://content.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${playlistId}&pageToken=${nextToken}&key=${apiKey}"
        }
        $url
        $responce=Invoke-RestMethod -Method Get -Uri $url
        $nextToken = $responce.nextPageToken
        $videoIds=$responce.items | foreach snippet
        # | foreach resourceId | foreach videoId
        $videoIds
        if ( $nextToken -eq $null ){
            return
        }
    }
}
function getDownloadVideoIdList{
    $videoIds = @()
    if( $downloadLog -ne "" -and ( Test-Path -path $downloadLog) ){
        Get-Content $downloadLog -Encoding UTF8 | ForEach-Object {
            $videoIds+=$_
        }
    }
    $videoIds
}
Main

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6