Powershell variable contains the value twice

Viewed 350

I have a powershell script that is started bij a jenskinsfile. This all works well. But in the script I have a function to download a file. This does not work, because the $filePath variable contains the value twice. When this part would be run the log would look like:

https://example.com/api/download
D:\folder\file_2.txt D:\folder\file_2.txt

How can I get the value only to be there ones in $filePath ?

function DownloadFile ($folder, $version) {

    $wc = New-Object System.Net.WebClient
    $wc.Headers['Content-Type'] = 'application/json'

    $requesturl = "https://example.com/api/download"
    $filePath = Join-Path -Path $folder -ChildPath "\file_$version.txt"

    Write-Host "$requesturl"
    Write-Host "$filePath"

    $wc.DownloadFile($requesturl, $filePath)

    return $filePath
}
1 Answers

The implication is that the argument you're passing to the -folder parameter (as represented inside your function as the $folder parameter variable) is an array of folder paths, not a single one.

The solution is therefore to make sure that you only pass a single folder path when you call your DownloadFile function; e.g.:

DownloadFile -folder D:\folder -version 2

# With *positional* parameter binding:
DownloadFile D:\folder 2

Since Join-Path accepts an array of paths as a -Path argument, it outputs multiple paths when given an array; e.g.:

PS> $folder = 'c:\abc', 'c:\def'; Join-Path -Path $folder -ChildPath file.txt
c:\abc\file.txt
c:\def\file.txt

Passing an array Write-Host implicitly stringifies it, which means creating a single string composed of the array elements joined with spaces:

PS> $folder = 'c:\abc', 'c:\def'; Write-Host $folder
c:\abc c:\def

(Note that this differs from implicit output / output via Write-Output, which prints each array element on its own line; also, implicit output / Write-Output write to the pipeline, meaning they output data for later processing, whereas Write-Host writes strings to the display).

Related