首页 > 解决方案 > 如何从带有 powershell 的链接中获取文件格式

问题描述

这是我的项目

cls


$url = Read-Host 'URL'
if ( $url -eq "")
{
    exit
}


[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.Forms")


function save-file([string]$initialDirectory)
{
    $savefile = New-Object System.Windows.Forms.SaveFileDialog

    $savefile.InitialDirectory = $initialDirectory
    $savefile.Filter="All files(*.*)|*.*"

    $savefile.ShowDialog() | out-null

    return $savefile.FileName

}


$file=save-file ""

if ( $file -eq "")
{
    exit
}
else
{
    echo "User Selected $file"
}



Invoke-WebRequest -Uri "$url" -OutFile "$file"

我将总结项目的想法

使用 powershell 从浏览器下载文件的程序。

我希望文件以链接格式自动保存

有没有办法使用 powershell 或 cmd 从链接获取文件格式?

我找到了我的问题的答案(我将把这个项目放在任何人都可以从中受益)

cls


$url = Read-Host 'URL'
if ( $url -eq "")
{
    exit
}

$dot = $url.Split(".")[-1]

[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.Forms")


function save-file([string]$initialDirectory)
{
    $savefile = New-Object System.Windows.Forms.SaveFileDialog

    $savefile.InitialDirectory = $initialDirectory
    $savefile.Filter="$dot file(*.$dot)|*.$dot"

    $savefile.ShowDialog() | out-null

    return $savefile.FileName

}


$file=save-file ""

if ( $file -eq "")
{
    exit
}
else
{
    echo "User Selected $file"
}



Invoke-WebRequest -Uri "$url" -OutFile "$file"

标签: powershelldownload

解决方案


To complement Hackoo's helpful answer with a slightly more robust version, which parses the URL (URI) via System.Uri:

PS> ([uri] 'https://example.org/downloads/foo.exe?other=stuff').Segments[-1]
foo.exe

The advantage of this approach is that any query-string suffix in the URL is ignored, which a strictly string-based parsing approach based on .Split() would not.

Append .Split('.')[-1] to get just the filename extension (exe, in the example above), as also shown in your updated question, or enclose in [System.IO.Path]::GetExtension(...) (which would yield .exe); in PowerShell (Core) 7+ you could also use Split-Path -Extension (also yields .exe).


推荐阅读