Script PowerShell per scaricare file da URL: Automatizza e verifica l'integrità dei file

di Team Ninja
Scaricare file da URL con PowerShell

Nel mondo frenetico dell'IT e dei servizi gestiti, l'efficienza e l'automazione sono fondamentali. Uno strumento particolarmente utile che ogni professionista IT o MSP dovrebbe avere nel proprio kit di strumenti è uno script PowerShell in grado di scaricare file da URL. In questo post del blog approfondiremo il funzionamento di uno script di questo tipo, parleremo degli scenari reali di utilizzo e illustreremo i vantaggi dell'uso di PowerShell per scaricare file da URL. 

Lo script: Scaricare file da URL con PowerShell

#Requires -Version 2.0

<#
.SYNOPSIS
    Downloads a file from a provided URL to a path.
.DESCRIPTION
    Downloads a file from a provided URL to a path. Can compare the hash and automatically remove the failed download.
    UserName and Password can be used for URL's that require it, basic authentication is expected.
.EXAMPLE
    -Url "https://www.google.com/" -FilePath "C:\temp\index.html"
    Downloads the index html page from google.com to C:\temp\index.html
.EXAMPLE
    -Url "https://www.nirsoft.net/utils/advancedrun.zip" -FilePath "C:\temp\advancedrun.zip" -Hash "b2c65aa6e71b0f154c5f3a8b884582779d716ff2c03d6cdca9e157f0fe397c9c" -Algorithm SHA256
    Downloads the advancedrun.zip file from nirsoft to C:\temp\advancedrun.zip and validates that the SHA256 hash matches
.EXAMPLE
    -Url "https://www.nirsoft.net/utils/advancedrun.zip" -FilePath "C:\temp\advancedrun.zip" -Hash "b2c65aa6e71b0f154c5f3a8b884582779d716ff2c03d6cdca9e157f0fe397c9c" -AutoRemove
    Downloads the advancedrun.zip file from nirsoft to C:\temp\advancedrun.zip and validates that the SHA256 hash matches. If the hash does not match the file will be removed.
    Not specifying Algorithm defaults to SHA256.
.OUTPUTS
    String[]
.NOTES
    Minimum OS Architecture Supported: Windows 7, Windows Server 2008 R2
    Release Notes:
    Initial Release
    (c) 2023 NinjaOne
    By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/it/condizioni-utilizzo/
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.COMPONENT
    Download
#>

[CmdletBinding()]
param (
    # Url that will be used to download a file
    [Parameter(Mandatory = $true)]
    [string]$Url,
    # File path that the file will be placed
    [Parameter(Mandatory = $true)]
    [string]$FilePath,
    # Expected hash of downloaded file
    [Parameter()]
    [string]$Hash,
    # Hashing Algorithm to use for hash comparison
    [Parameter()][ValidateSet("SHA1", "SHA256", "SHA384", "SHA512", "MD5")]
    [string]$Algorithm = "SHA256",
    # Removes failed download automatically
    [Parameter()]
    [switch]$AutoRemove,
    # UserName
    [Parameter()]
    [string]$UserName,
    # Password
    [Parameter()]
    [string]$Password
)

# For PowerShell 2.0 and 3.0 compatibility
if ($PSVersionTable.PSVersion.Major -lt 4) {
    function Get-FileHash {
        param (
            [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
            [string[]]
            $Path,
            [Parameter(Mandatory = $false)]
            [ValidateSet("SHA1", "SHA256", "SHA384", "SHA512", "MD5")]
            [string]
            $Algorithm = "SHA256"
        )
        $Path | ForEach-Object {
            # Only hash files that exist
            $CurrentPath = $_
            if ($(Test-Path -Path $CurrentPath -ErrorAction SilentlyContinue)) {
                
                $HashAlgorithm = New-Object -TypeName System.Security.Cryptography.$($Algorithm)CryptoServiceProvider
                $Hash = [System.BitConverter]::ToString($hashAlgorithm.ComputeHash([System.IO.File]::ReadAllBytes($CurrentPath)))
                @{
                    Algorithm = $Algorithm
                    Path      = $Path
                    Hash      = $Hash.Replace('-', '')
                }
            }
        }
    }
}

# For PowerShell 2.0 compatibility
if ($PSVersionTable.PSVersion.Major -le 2) {
    $client = New-Object System.Net.WebClient
    if ($PSBoundParameters.ContainsKey("UserName") -and $PSBoundParameters.ContainsKey("Password")) {
        $client.Credentials = New-Object System.Net.NetworkCredential($UserName, $(ConvertTo-SecureString -String $Password -AsPlainText -Force))
    }
    elseif (
        ($PSBoundParameters.ContainsKey("UserName") -and -not $PSBoundParameters.ContainsKey("Password")) -or
        (-not $PSBoundParameters.ContainsKey("UserName") -and $PSBoundParameters.ContainsKey("Password"))
    ) {
        Write-Error "UserName and Password parameters have to be used together."
        exit 1
    }
    try {
        if ($null -ne $FilePath) {
            $client.DownloadFile($Url, $FilePath)
        }
        else {
            # Similar functionality to Invoke-WebRequest if -OutFile was not used, null, or an empty string
            # Defaults to the current directory
            $client.DownloadFile($Url, ".\")
        }
        
    }
    catch {
        Write-Error $_
        Write-Host "System.Net.WebClient Failed to download from $Url to $FilePath"
        exit 1
    }
}
else {
    $Splat = @{
        Uri        = $Url
        OutFile    = $FilePath
        Credential = if ($PSBoundParameters.ContainsKey("UserName") -and $PSBoundParameters.ContainsKey("Password")) {
            New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserName, $SecureString
        }
        else { $null }
    }
    try {
        Invoke-WebRequest @Splat
    }
    catch {
        Write-Error $_
        Write-Host "Invoke-WebRequest failed to download from $Url to $FilePath"
        exit 1
    }
    
}
Write-Host "Computing hash using $Algorithm"
$ComputedHash = $(Get-FileHash -Path $FilePath -Algorithm $Algorithm).Hash
Write-Host "Computed hash for $FilePath is $ComputedHash"
if ($PSBoundParameters.ContainsKey("Hash")) {
    if ($ComputedHash -like $Hash) {
        Write-Host "$FilePath hash matched!"
    }
    else {
        Write-Error "$FilePath hash did not match!"
        Write-Host "Computed hash of $FilePath was:"
        Write-Host "$ComputedHash"
        Write-Host "Expected hash was:"
        Write-Host "$Hash"
        if ($AutoRemove) {
            Write-Host "Removing failed download."
            try {
                # This should always remove the file
                Remove-Item $Path -Force -Confirm:$false -ErrorAction SilentlyContinue
                Write-Host "Removed failed download."
            }
            catch {
                if ($(Test-Path -Path $Path -ErrorAction SilentlyContinue)) {
                    Write-Host "Failed to remove failed download."
                }
                else {
                    Write-Host "Removed failed download."
                }
            }
        }
        exit 1
    }
}

Accedi a oltre 700 script nel Dojo di NinjaOne Ottieni l'accesso

Scenari reali di utilizzo: Come usare lo script

Questo script per scaricare file da URL ha un ampio ventaglio di applicazioni.

Scaricare regolarmente gli aggiornamenti

Se stai gestendo una rete in cui gli aggiornamenti software vengono rilasciati come file scaricabili sul sito web di un fornitore, puoi automatizzare il processo di download con questo script.

Raccolta dati

Se stai raccogliendo dei dati dal Web per un’analisi e i dati vengono forniti come file scaricabili, questo script può automatizzare il processo e garantire che i dati scaricati siano intatti.

Automatizzare il backup delle risorse online

Se la tua organizzazione conserva file o risorse importanti online, puoi usare questo script per automatizzare i download regolari a scopo di backup.

Perché usare PowerShell per scaricare file da URL?

Automazione

L'automazione è un vantaggio fondamentale di questo script PowerShell per scaricare file da URL. Automatizzando il processo per scaricare file da URL, puoi risparmiare tempo, ridurre la possibilità di errore umano e concentrarti su attività più complesse che non possono essere automatizzate. 

Efficienza

L’utilizzo di PowerShell per scaricare file da URL può anche aumentare l'efficienza. Potrai gestire un gran numero di download senza dover navigare manualmente verso ogni URL per avviare il processo di download. 

Verifica dell'integrità dei file

Lo script per scaricare file da URL ha una funzionalità che confronta gli hash e che garantisce l'integrità dei file scaricati. Confrontare l'hash del file scaricato con l'hash previsto aiuta a verificare che il file sia stato scaricato correttamente e non sia danneggiato, e permette di essere tranquilli quando si distribuiscono patch o aggiornamenti in rete. 

Considerazioni finali

Come abbiamo visto, gli script di PowerShell possono semplificare le operazioni IT ed è qui che NinjaOne può rivelarsi particolarmente prezioso. Si tratta di una suite completa di monitoraggio e gestione IT che supporta l'uso di script come quello qui descritto per automatizzare le attività di routine e gestire l'infrastruttura IT in modo più efficiente. La possibilità di scaricare file da URL e di convalidarne l'integrità è solo un esempio di ciò che si può ottenere con NinjaOne. Integrando questi script nella solida piattaforma di NinjaOne, potrai ulteriormente migliorare le operazioni IT e avere un approccio più proattivo ed efficiente alla gestione dell'ambiente IT.  

Accedi a questo script e a centinaia di altri all'interno di NinjaOne. 

Passi successivi

La creazione di un team IT efficiente ed efficace richiede una soluzione centralizzata che funga da principale strumento di erogazione dei servizi. NinjaOne consente ai team IT di monitorare, gestire, proteggere e supportare in termini di assistenza tutti i dispositivi, ovunque essi si trovino, senza la necessità di una complessa infrastruttura locale.
Scopri qualcosa in più su Ninja Endpoint Management, fai un tour dal vivo o inizia la tua prova gratuita della piattaforma NinjaOne.

NinjaOne si è classificato al primo posto per RMM, Endpoint Management e Patch Management

Monitora, gestisci e proteggi qualsiasi dispositivo, in qualsiasi luogo

NinjaOne gives you complete visibility and control over all your devices for more efficient management.

Un numero eccessivo di tool in location separate?

Scopri come la disseminazione di strumenti ha un impatto sull'IT e cosa si può fare per risolverla.