# provide the path to the folder where the NuGet package should be extracted
# use a full path, e.g. "C:\MySubfolder\MyFolder"
$destinationFolder = "C:\MySubfolder\MyFolder"
# Fill this variable with the version from the powershell gallery you want to extract
$PowerShellGetVersion = "2.2.5"
$PackageManagementVersion = "1.4.8.1"

# Define the NuGet package name
$PowerShellGet = "PowerShellGet"
$PackageManagement = "PackageManagement"

function ExtractAndCleanNugetPackage {
  param(
      [string]$destinationFolder,
      [string]$nugetPackageName,
      [string]$version
  )
  $extractPath = "$destinationFolder\$nugetPackageName"
  $installationPath = "$extractPath\$version"
  if (!(Test-Path -Path $installationPath)) {
    New-Item -ItemType Directory -Force -Path $installationPath
  }
  # Download the NuGet package
  $nugetUrl = "https://www.powershellgallery.com/api/v2/package/$nugetPackageName/$version"
  Invoke-WebRequest -Uri $nugetUrl -OutFile "$extractPath\$nugetPackageName.nupkg"

  # Unblock the downloaded file, rename it to .zip because Expand-Archive does not support .nupkg files and extract it
  Unblock-File -Path "$extractPath\$nugetPackageName.nupkg"
  Rename-Item -Path "$extractPath\$nugetPackageName.nupkg" -NewName "$extractPath\$nugetPackageName.zip"
  Expand-Archive -Path "$extractPath\$nugetPackageName.zip" -DestinationPath $installationPath -Force

  # Delete nuget specific files and the downloaded zip file
  $folderToDelete = "_rels"
  $folderToDelete2 = "package"
  $fileToDelete = "$nugetPackageName.nuspec"
  $fileToDelete2 = "`[Content_Types`].xml"
  Remove-Item -Path "$installationPath\$folderToDelete" -Recurse
  Remove-Item -Path "$installationPath\$folderToDelete2" -Recurse
  Remove-Item -Path "$installationPath\$fileToDelete" -Force
  Remove-Item -LiteralPath "$installationPath\$fileToDelete2" -Force
  Remove-Item -Path "$extractPath\$nugetPackageName.zip" -Force

  # Unblock all files in the extracted folder to avoid security warnings
  Get-ChildItem -Path $installationPath -Recurse | Unblock-File
}

ExtractAndCleanNugetPackage -destinationFolder $destinationFolder -nugetPackageName $PowerShellGet -version $PowerShellGetVersion
ExtractAndCleanNugetPackage -destinationFolder $destinationFolder -nugetPackageName $PackageManagement -version $PackageManagementVersion