xDSCDownloadFile.psm1
Enum TransferEncoding { Chunked Compress Deflate GZip Identity } enum Ensure { Absent Present } [DscResource()] class xDSCDownloadFile { [DsCProperty(Key)] [String] $Url [DsCProperty(Mandatory)] [Ensure] $Ensure [DsCProperty(Mandatory)] [String] $Destination [DsCProperty()] [PsCredential] $Credential [DsCProperty()] [TransferEncoding] $TransferEncoding [DsCProperty()] [HashTable] $Headers [DsCProperty()] [String] $Proxy [DsCProperty()] [PsCredential] $ProxyCredential [DsCProperty()] [uint32] $TimeoutSec [DsCProperty()] [Bool] $UseDefaultCredentials [DsCProperty(NotConfigurable)] [Boolean] $IsValid [xDSCDownloadFile] Get() { $this.IsValid = $false $fileExists = Test-Path -LiteralPath $this.Destination if($this.Ensure -eq [Ensure]::Present) { if($fileExists) { $this.IsValid = $true } } else { if(-not $fileExists) { $this.IsValid = $true } } return $this } [void] Set() { if($this.Ensure -eq [Ensure]::Present) { $Invoke = [Hashtable]::new() $Invoke.Uri = $this.Url $Invoke.OutFile = $this.Destination if($this.Credential){ $Invoke.Credential = $this.Credential } if($this.TransferEncoding){ $Invoke.TransferEncoding = $this.TransferEncoding } if($this.Headers){ $Invoke.Headers = $this.Headers } if($this.Proxy){ $Invoke.Proxy = $this.Proxy } if($this.ProxyCredential){ $Invoke.ProxyCredential = $this.ProxyCredential } if($this.TimeoutSec){ $Invoke.TimeoutSec = $this.TimeoutSec } if($this.UseDefaultCredentials){ $Invoke.UseDefaultCredentials = $this.UseDefaultCredentials } [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $null = Invoke-WebRequest @Invoke -ErrorAction Stop } else { Remove-Item -LiteralPath $this.Destination -Force -Confirm:$false } } [bool] Test() { $result = $this.Get() if($this.Ensure -eq [Ensure]::Present) { if($result.IsValid) { Write-Verbose "The file from the Url $($this.Url) already exist." return $true } else { Write-Verbose "The file from the Url $($this.Url) does not exists. This will be downloaded" return $false } } else { if($result.IsValid) { Write-Verbose "The file from the Url $($this.Url) does not exists" return $true } else { Write-Verbose "The file from the Url $($this.Url) exists. This will be be removed" return $false } } } } |