Franck Deny
Franck Deny

Reputation: 39

Powershell script - manage empty parameters

Am automating youtubeDl tasks with Powershell via some functions in profile.ps1 This function accepts different parameters - if some are set, i'll setup additional config to youtube-dl executable.

For instance, executing ytDl https://vimeo.com/1548390390 would result in executing .\youtube-dl.exe https://vimeo.com/1548390390. When executing ytDl https://vimeo.com/1548390390 3458F89 would lead to .\youtube-dl.exe https://vimeo.com/1548390390 --video-password 3458F89

Am able to do what i want working script is not "beautiful"/"clean". I pasted below the two versions.

Can anyone of you help me - explain me why it's not behaving as expected ? Thanks a lot !

function ytDl_Working_But_NotBeautiful {
    param (
        [Parameter(Mandatory = $true, Position = 0)][string]$url,
        [Parameter(Mandatory = $false, Position = 1)][string]$password,
        [Parameter(Mandatory = $false, Position = 2)][string]$youtubeDlPath = "C:\APPS\"
    )
        Write-Host "URL = $url || Password = $password"
        
        cd $youtubeDlPath
        
        if ($password.Length -gt 0) {
            Write-Host "Password set - adding video-password parameter"
            .\youtube-dl.exe $url --video-password $password
        }
        else{
            .\youtube-dl.exe $url
        }
}

function ytDl_NotWorking {
    param (
        [Parameter(Mandatory = $true, Position = 0)][string]$url,
        [Parameter(Mandatory = $false, Position = 1)][string]$password,
        [Parameter(Mandatory = $false, Position = 2)][string]$youtubeDlPath = "C:\APPS\"
    )
        Write-Host "URL = $url || Password = $password"
        
        $fullParams = $url
        if ($password.Length -gt 0) {
            Write-Host "Password set - adding video-password parameter"
            $fullParams = "$url --video-password $password"
        }
        Write-Host ".\youtube-dl.exe $fullParams"
        
        .\youtube-dl.exe $fullParams
}

Upvotes: 0

Views: 164

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

If you want to pass a variable number of arguments to an executable without having to write many nested if/else statements, take advantage of splatting!

function Save-OnlineVideo
{
    param (
        [Parameter(Mandatory = $true, Position = 0)][string]$url,
        [Parameter(Mandatory = $false, Position = 1)][string]$password,
        [Parameter(Mandatory = $false, Position = 2)][string]$youtubeDlPath = "C:\APPS\"
    )

    # Create array to hold the arguments
    $fullParams = @($url)

    if ($password.Length -gt 0) {
        # Add any additional arguments to the array
        $fullParams += "--video-password","$password"
    }

    # prepend variable name with @ instead of $ to make powershell splat them
    .\youtube-dl.exe @fullParams
}

Upvotes: 2

Related Questions