common.psm1 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. $ErrorActionPreference = 'Stop'
  2. # Update the default TLS support to 1.2
  3. [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
  4. function Invoke-Block([scriptblock]$cmd, [string]$WorkingDir = $null) {
  5. if ($WorkingDir) {
  6. Push-Location $WorkingDir
  7. }
  8. try {
  9. $cmd | Out-String | Write-Verbose
  10. & $cmd
  11. # Need to check both of these cases for errors as they represent different items
  12. # - $?: did the powershell script block throw an error
  13. # - $lastexitcode: did a windows command executed by the script block end in error
  14. if ((-not $?) -or ($lastexitcode -ne 0)) {
  15. if ($error -ne $null)
  16. {
  17. Write-Warning $error[0]
  18. }
  19. throw "Command failed to execute: $cmd"
  20. }
  21. }
  22. finally {
  23. if ($WorkingDir) {
  24. Pop-Location
  25. }
  26. }
  27. }
  28. function SaveXml([xml]$xml, [string]$path) {
  29. Write-Verbose "Saving to $path"
  30. $ErrorActionPreference = 'stop'
  31. $settings = New-Object System.XML.XmlWriterSettings
  32. $settings.OmitXmlDeclaration = $true
  33. $settings.Encoding = New-Object System.Text.UTF8Encoding( $true )
  34. $writer = [System.XML.XMLTextWriter]::Create($path, $settings)
  35. $xml.Save($writer)
  36. $writer.Close()
  37. }
  38. function LoadXml([string]$path) {
  39. Write-Verbose "Reading from $path"
  40. $ErrorActionPreference = 'stop'
  41. $obj = new-object xml
  42. $obj.PreserveWhitespace = $true
  43. $obj.Load($path)
  44. return $obj
  45. }
  46. function Get-RemoteFile([string]$RemotePath, [string]$LocalPath) {
  47. if ($RemotePath -notlike 'http*') {
  48. Copy-Item $RemotePath $LocalPath
  49. return
  50. }
  51. $retries = 10
  52. while ($retries -gt 0) {
  53. $retries -= 1
  54. try {
  55. Invoke-WebRequest -UseBasicParsing -Uri $RemotePath -OutFile $LocalPath
  56. return
  57. }
  58. catch {
  59. Write-Verbose "Request failed. $retries retries remaining"
  60. }
  61. }
  62. Write-Error "Download failed: '$RemotePath'."
  63. }