2016-07-03 77 views
3

如何跳過文件下載使用PowerShell我有以下腳本,它從下載通道9一些文件:如果文件存在

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' 

我需要改善它跳過下載,如果文件已經存在。

回答

2

您必須將整個路徑傳遞給Test-Path cmdlet以檢查文件是否存在。那麼你所要做的就是return的功能:

# .... 
$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