cDownloadFile.psm1
[DscResource()] class cDownloadFile { #This property is the url of the file to be downloaded [DscProperty(Key)] [string]$Url #This is the fully qualified path for the file that is expected to be 'Present' or 'Absent' [DscProperty(Mandatory)] [string]$OutputFolderPath [DscProperty()] [bool] $UpdateOnDiff [DscProperty()] [string]$SASToken [void]Set() { $filePath = (Resolve-Path $this.OutputFolderPath).Path if((Get-Item $filePath)-is [System.IO.DirectoryInfo]){ $fileName = $this.Url.Split('/')[-1] $filePath = $filePath + "\" + $fileName } $downloadUrl = $this.Url + $this.SASToken Write-Verbose "Changing Protocol to TLS 1.2" [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 write-verbose "Starting download from url: $downloadUrl" $client = New-Object System.Net.WebClient $client.DownloadFile($downloadUrl,$filePath) } [bool]Test() { Write-Verbose "Checking if $($this.OutputFolderPath) exists" try { $filePath = (Resolve-Path $this.OutputFolderPath).Path } catch { throw New-Object -TypeName System.InvalidOperationException -ArgumentList "OutputFolderPath should be a valid existing folder" } if($this.SASToken -ne $null) { $downloadUrl = $this.Url + $this.SASToken } else { $downloadUrl = $this.Url } Write-Verbose "Checking for File:" $fileName = $this.Url.Split('/')[-1] Write-Verbose "FileName = $fileName" $IsFileThere = $false if((Get-Item $filePath)-is [System.IO.DirectoryInfo]){ $filePath = $filePath + "\" + $fileName $IsFileThere = Test-Path $filePath } if($IsFileThere){ Write-Verbose "File Exists" if(!$this.UpdateOnDiff){ return $true } $file = Get-Item $filePath [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 $client = New-Object System.Net.WebClient $client.OpenRead($downloadUrl) $ServerFileLength = $client.ResponseHeaders['Content-Length'] Write-Verbose "Length = $ServerFileLength" if($ServerFileLength -eq $file.Length){ Write-Verbose 'File on server is identical to from existing file.' return $true } } Write-Verbose "New version of file not found!" return $false } [cDownloadFile]Get() { $returnValue = @{ Url = [System.String] OutputFolderPath = [System.String] UpdateOnDiff = [System.Boolean] SASToken = [System.String] } return $returnValue } } |