Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
DocumentaryTube
automation

How to Build a PowerShell Playlist Rotation Script for Multiple YouTube Streams

A practical PowerShell example for reading multiple YouTube playlists and selecting videos locally, plus the key distinction between playlist items and live broadcasts.

By DocumentaryTube Team 6 min read
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can build a PowerShell script that reads several YouTube playlists, collects their video IDs, and rotates through them in a local player or downstream workflow. First, decide what “multiple YouTube streams” means: YouTube playlists, whose items are videos, or scheduled live broadcasts, which are events connected to incoming live feeds. Those are different YouTube API resources and need different scripts.

Choose what the script will rotate

YouTube does not treat a playlist as a live stream. A playlistItem identifies a resource—usually a video—inside a playlist. A liveBroadcast is an event viewers watch, while a liveStream is the incoming audio/video feed. Google’s playlist item reference and live broadcast reference describe those separate resources.

What you want to rotate Relevant YouTube resource What the script does
Which video to play next Playlist items and video IDs Reads playlist contents and selects the next ID locally; it need not change YouTube playlist order.
The order of videos in a YouTube playlist Playlist items Uses authorized write operations to modify playlist resources.
Which scheduled live event is active Live broadcasts bound to live streams Checks event and feed state, then transitions the intended broadcast.

The example below handles the first case: multiple playlist IDs, read-only retrieval, and local round-robin selection. It does not start an encoder, edit playlist order, or transition live events.

Set up access and configuration

Prepare the YouTube API project

  1. In Google Cloud, create or select a project, enable the YouTube Data API v3, and configure OAuth consent and credentials for your application. The YouTube Data API overview explains project setup and quota.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
    #1 Best Overall
    Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
    • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
    • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
    • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
    • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
    • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
  2. Obtain an OAuth access token for the Google account that can see the target playlists. A public API key is not authorization to access private account data or make playlist changes. For this read-only script, use an OAuth scope sufficient to read the playlists you intend to access; use the least privilege compatible with your account and application.

  3. Keep the access token out of the script and source control. The example expects it in the YOUTUBE_ACCESS_TOKEN environment variable. Access tokens expire; your OAuth flow or credential manager must refresh or replace the token when needed.

  4. Choose your PowerShell version, how you obtain and refresh OAuth credentials, playlist IDs, rotation interval, and what consumes the selected video ID. This example uses raw REST calls and runs once per invocation; a scheduler or calling application can invoke it repeatedly.

    Rank #2
    Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
    • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
    • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
    • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
    • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
    • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Record the playlist IDs

Supply each playlist with a label and its playlist ID. The label is for your own logs; the ID is the value sent as playlistId to the API. The playlist-items list method accepts a playlist ID and returns item metadata including the referenced video ID and playlist position. See Google’s list method reference.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Example: read several playlists and choose the next video

Save this as Rotate-YouTubePlaylists.ps1. It fetches all pages for each configured playlist, orders results by the playlist position returned in the snippet, and selects one video per playlist in a round-robin pass. It prints JSON; replace that output step with an integration appropriate to your local player or workflow.

$ErrorActionPreference = 'Stop'

$accessToken = $env:YOUTUBE_ACCESS_TOKEN
if ([string]::IsNullOrWhiteSpace($accessToken)) {
    throw 'Set YOUTUBE_ACCESS_TOKEN to an OAuth access token before running this script.'
}

# Replace these examples with the playlist IDs the authorized account can access.
$playlists = @(
    [pscustomobject]@{ Name = 'Documentaries'; Id = 'PL_REPLACE_WITH_ID_1' },
    [pscustomobject]@{ Name = 'Interviews';    Id = 'PL_REPLACE_WITH_ID_2' }
)

function Get-YouTubePlaylistItems {
    param(
        [Parameter(Mandatory)][string]$PlaylistId,
        [Parameter(Mandatory)][string]$Token
    )

    $items = [System.Collections.Generic.List[object]]::new()
    $pageToken = $null

    do {
        $query = @{
            part       = 'snippet,contentDetails,status'
            playlistId = $PlaylistId
            maxResults = 50
        }
        if ($pageToken) { $query.pageToken = $pageToken }

        $queryString = ($query.GetEnumerator() | ForEach-Object {
            '{0}={1}' -f [uri]::EscapeDataString([string]$_.Key),
                         [uri]::EscapeDataString([string]$_.Value)
        }) -join '&'
        $uri = 'https://www.googleapis.com/youtube/v3/playlistItems?' + $queryString
        $response = Invoke-RestMethod -Method Get -Uri $uri -Headers @{
            Authorization = "Bearer $Token"
        }

        foreach ($item in $response.items) {
            $videoId = $item.snippet.resourceId.videoId
            if ($videoId) {
                $items.Add([pscustomobject]@{
                    PlaylistId = $PlaylistId
                    Position   = [int]$item.snippet.position
                    VideoId    = [string]$videoId
                    Title      = [string]$item.snippet.title
                })
            }
        }
        $pageToken = $response.nextPageToken
    } while ($pageToken)

    return $items | Sort-Object Position
}

$queues = foreach ($playlist in $playlists) {
    if ($playlist.Id -like '*REPLACE*') {
        throw "Replace the placeholder playlist ID for '$($playlist.Name)'."
    }
    $items = @(Get-YouTubePlaylistItems -PlaylistId $playlist.Id -Token $accessToken)
    if ($items.Count -eq 0) {
        Write-Warning "Playlist '$($playlist.Name)' returned no video items."
        continue
    }
    [pscustomobject]@{ Name = $playlist.Name; Items = $items }
}

# One selected item from each non-empty playlist, in configured playlist order.
$rotation = foreach ($queue in $queues) {
    [pscustomobject]@{
        Playlist = $queue.Name
        VideoId  = $queue.Items[0].VideoId
        Title    = $queue.Items[0].Title
    }
}

$rotation | ConvertTo-Json -Depth 4

What this example does—and does not—remember

Each run starts at the first video in each playlist. To advance through each playlist across repeated runs, persist a cursor per playlist outside the process—for example, in a state file or database—and update it only after the consumer has successfully handled the selected video. If you only need to choose the next video at runtime, keep that cursor locally rather than modifying YouTube’s playlist.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

The code handles API pagination using nextPageToken, but it is an implementation example, not a tested script. Adapt and validate it in your PowerShell version and OAuth setup before scheduling it. In production, log playlist ID, selected video ID, timestamp, and API error details without logging the access token.

If you mean rotating scheduled live broadcasts

Do not use playlist-item operations to switch live events. Configure broadcast IDs and their intended stream bindings per channel, then read the relevant broadcast and bound stream state before taking action. Google’s guide to understanding broadcasts and streams documents the distinction and a common recurring-event pattern: one stream bound to multiple broadcasts, with one event live at a time. For multiple channels in that scenario, the guide calls for a different stream for each channel.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Retrieve the intended broadcast and verify its bound stream. Do not assume a playlist change affects the feed.

    Rank #4
    Sale
    UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
    • Dual Converters, Infinite Potential:Includes 2Ă— USB C male to USB A female adapters and 2Ă— USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
    • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
    • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
    • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
    • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
  2. Before requesting a testing or live transition, confirm the bound stream’s status.streamStatus is active, as specified by the broadcast transition reference.

  3. Request only the intended lifecycle transition and record the response and resulting state. A transition changes broadcast lifecycle and can initiate testing or live behavior; it is not equivalent to selecting the next playlist video.

Build explicit checks around broadcast ownership, channel context, current lifecycle state, intended stream binding, and the transition you permit. The API documentation defines these resources and operations, but a complete event-rotation implementation depends on your broadcast setup and authorization flow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Authorization, quota, and safe operation

Run it on a schedule

A Windows Scheduled Task or another scheduler can invoke the script at your chosen interval. The exact task configuration depends on the machine, account context, PowerShell version, and credential-handling approach. Ensure the scheduled identity can access the token or credential refresh mechanism, capture standard output and errors, and avoid putting bearer tokens directly in task arguments or logs. For a persistent rotation cursor, protect the state store from concurrent runs so two invocations do not select or advance the same entry unexpectedly.

Or let it run in the cloud

If your goal is to keep uploaded videos playing as a 24/7 YouTube stream rather than write and operate a rotation script, StreamNeo runs the uploaded videos from the cloud. Upload your recording or build a playlist, add your YouTube stream key once, and go live. Nothing has to stay on at home; videos stream as uploaded at any quality up to 4K 60fps for one flat price per slot, and StreamNeo automatically recovers if YouTube drops the stream. The first day is free with no card. Monthly: $9.99 per month.

Start your free day with StreamNeo.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Screening Room

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.