如何使用 powershell 从 link 获取文件格式

How to get the file format from a link with 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 从浏览器下载文件的程序。

我希望文件自动保存为link格式

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

我找到了问题的答案(我会把这个项目放上去,这样任何人都可以从中受益)

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"

如果你的意思是如何从直接 link 中提取文件名:

$URL = "https://cdn2.unrealengine.com/Fortnite%2FBoogieDown_GIF-1f2be97208316867da7d3cf5217c2486da3c2fe6.gif"
$FileName = $URL.Split("/")[-1]
$FileName

如果您想避免使用 BrowseForFolder 并自动保存在脚本第一次执行时创建的文件夹中,请按照他的方式尝试:

$DownloadFolder = $Env:AppData + "\DownloadFolder\"
# Create a Download Folder if not exist yet to store files that will be downloaded in the future
If ((Test-Path -Path $DownloadFolder) -eq 0) { New-Item -Path $DownloadFolder -ItemType Directory | Out-Null }
$url = Read-Host 'URL'
$FileName = $url.Split("/")[-1]
if ( $url -eq ""){exit}
$FilePath = $DownloadFolder+$FileName
Write-Host "The file will be saved in this path ""$FilePath""" -Fore Green 
If ($FileName -eq ""){Exit} Else {Invoke-WebRequest -Uri "$url" -OutFile "$FilePath"}

补充 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

这种方法的优点是 URL 中的任何 query-string 后缀都被 忽略 ,严格来说基于字符串的解析方法不会基于.Split()

追加 .Split('.')[-1] 以仅获取文件名 extensionexe,在上面的示例中),如您更新的问题中所示,或附上在 [System.IO.Path]::GetExtension(...) (which would yield .exe); in PowerShell (Core) 7+ you could also use Split-Path -Extension 中(也产生 .exe)。