Home > Software engineering >  How to get the file format from a link with powershell
How to get the file format from a link with powershell

Time:11-07

This is my project

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"

I will summarize the idea of the project

A program that downloads files from the browser using powershell.

I want the file to be saved automatically in the link format

Is there a way to get the file format from a link using powershell or cmd?

CodePudding user response:

If you mean how to extract the file name from a direct link like this one :

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

And if you want avoid to use BrowseForFolder and save automatically in a folder that will be created by the script for the first time of execution, try like his way :

$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"}
  • Related