测试路径:路径中存在非法字符

Lui*_*cia 2 powershell

我正在尝试使用 powershell 从 Channel9 下载视频系列,但是我在第一个文件上收到此错误,我认为它是管道字符,但即使使用替换语句它也不起作用

\n\n
 function Get-Media\n{\n    [CmdletBinding()]\n    param\n    (\n        [Object]\n        $url,\n        [Object]\n        $title,\n        [Object]\n        $path\n    )\n\n    $u = New-Object System.Uri($url)\n    $name = $title\n    $extension = [System.IO.Path]::GetExtension($u.Segments[-1])\n    $fileName = $name + $extension\n\n    $fileName = $fileName -replace "\xc3\xa2\xe2\x82\xac\xe2\x84\xa2", \'\'\n    $fileName = $fileName -replace "\\?", \'\'\n    $fileName = $fileName -replace ":", \'\'\n    $fileName = $fileName -replace \'/\', \'\'\n    $fileName = $fileName -replace ",", \'\'\n    $fileName = $fileName -replace \'"\', \'\'\n    $fileName = $fileName -replace \'|\', \'\'\n    $fileName = $fileName -replace \'\\#\', \'\'\n    $fileName = $fileName -replace \'-\', \'\'\n\n    $fileName\n\n    if (Test-Path($fileName)) {\n        Write-Host \'Skipping file, already downloaded\' -ForegroundColor Yellow\n    }\n    else\n    {\n        Invoke-WebRequest $url -OutFile (Join-Path -Path $path -ChildPath $fileName)\n    }\n}\n\nfunction Get-VideosFromFeed\n{\n    [CmdletBinding()]\n    param\n    (\n        [Object]\n        $feedUrl,\n        [Object]\n        $folder,\n        [Object]\n        $path\n    )\n\n    $feed=[xml](New-Object System.Net.WebClient).DownloadString($feedUrl)\n\n    $downloadPath = (Join-Path -Path $path -ChildPath $folder)\n\n    if (Test-Path($downloadPath)) {\n        Write-Host \'Skipping folder, already exists\' -ForegroundColor Yellow\n    }\n    else\n    {\n        New-Item -Path $downloadPath -ItemType directory -WarningAction SilentlyContinue\n    }\n\n    foreach($i in $feed.rss.channel.item) {\n        foreach($m in $i.group){\n            foreach($u in $m.content `\n                    | Where-Object { `\n                            $_.url -like \'*mid.mp4\' `\n                         } | Select-Object -Property @{Name=\'url\'; Expression = {$_.url}}, `\n                                                     @{Name=\'title\'; Expression = {$i.title}})\n            {\n                Get-Media -url $u.url -title $u.title -path $downloadPath\n            }\n        }\n    }\n}\n\n$physicalPath = "D:\\Videos\\Series"\n\nGet-VideosFromFeed -feedUrl \'https://channel9.msdn.com/Blogs/azurestack/feed/mp4high\'                                                                          -path $physicalPath -folder \'azurestack\'\n
Run Code Online (Sandbox Code Playgroud)\n

Nul*_*ata 5

你也可以尝试这个:

$FileName.Split([IO.Path]::GetInvalidFileNameChars()) -join ''
Run Code Online (Sandbox Code Playgroud)

对我来说似乎很有效:)

  • 与 n01d 的答案相比,我更喜欢这个答案。这样您就可以将字符列表的责任交给操作系统。它奏效了。 (2认同)