Question:
I have the following script which downloads some files from channel 9:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
function Get-Media { [CmdletBinding()] param ( [Object] $url, [Object] $title, [Object] $path ) $u = New-Object System.Uri($url) $name = $title $extension = [System.IO.Path]::GetExtension($u.Segments[-1]) $fileName = $name + $extension #$fileName = $fileName -replace "’", '' #$fileName = $fileName -replace "\?", '' #$fileName = $fileName -replace ":", '' #$fileName = $fileName -replace '/', '' #$fileName = $fileName -replace ",", '' #$fileName = $fileName -replace '"', '' #$fileName = $fileName -replace '|', '' #$fileName = $fileName -replace '\#', '' #$fileName = $fileName -replace '-', '' $fileName = $fileName -replace '(-|#|\||"|,|/|:|â|€|™|\?)', '' if (Test-Path($fileName)) { Write-Host 'Skipping file, already downloaded' -ForegroundColor Yellow } else { Invoke-WebRequest $url -OutFile (Join-Path -Path $path -ChildPath $fileName) } } function Get-VideosFromFeed { [CmdletBinding()] param ( [Object] $feedUrl, [Object] $folder, [Object] $path ) $feed=[xml](New-Object System.Net.WebClient).DownloadString($feedUrl) $downloadPath = (Join-Path -Path $path -ChildPath $folder) if (Test-Path($downloadPath)) { Write-Host 'Skipping folder, already exists' -ForegroundColor Yellow } else { New-Item -Path $downloadPath -ItemType directory -WarningAction SilentlyContinue } foreach($i in $feed.rss.channel.item) { foreach($m in $i.group){ foreach($u in $m.content ` | Where-Object { ` $_.url -like '*mid.mp4' ` } | Select-Object -Property @{Name='url'; Expression = {$_.url}}, ` @{Name='title'; Expression = {$i.title}}) { Get-Media -url $u.url -title $u.title -path $downloadPath } } } } $physicalPath = "D:\Videos\Series" Get-VideosFromFeed -feedUrl 'https://channel9.msdn.com/Series/Deep-Dive-into-the-Office-365-App-Model/feed/mp4high' -path $physicalPath -folder 'Deep-Dive-into-the-Office-365-App-Model' |
I need to improve it to skip the download if the file already exists.
Answer:
You have to pass the whole path to the Test-Path
cmdlet to check whether the file exist. Then all you have to do is to return
the function:
1 2 3 4 5 6 7 8 9 10 11 12 |
# .... $fileName = $fileName -replace '(-|#|\||"|,|/|:|â|€|™|\?)', '' $filePath = Join-Path $path $fileName if (Test-Path($filePath)) { Write-Host 'Skipping file, already downloaded' -ForegroundColor Yellow return } Invoke-WebRequest $url -OutFile $filePath |