Skip to content

Instantly share code, notes, and snippets.

@hkarthik7
Created February 18, 2021 16:20
Show Gist options
  • Save hkarthik7/1b6a7d3ed5104b872da5a39f56b8edea to your computer and use it in GitHub Desktop.
Save hkarthik7/1b6a7d3ed5104b872da5a39f56b8edea to your computer and use it in GitHub Desktop.
Downloads https log files from SCM API
function Export-AzureWebAppLogFiles {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]
$AppServiceName,
[Parameter(Mandatory = $true)]
[string]
$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]
$LogFilePath,
# if you want to download the logfiles as zip
# then you have to provide the file path with .zip extension.
# e.g., C:\Temp\Logs.zip
[Parameter(Mandatory = $true)]
[string]
$ExportPath,
[Parameter(Mandatory = $false)]
[switch]
$Zip
)
begin {
$functionName = $MyInvocation.MyCommand.Name
$LogFilePath = $LogFilePath.TrimEnd("/")
$scm = "https://$($AppServiceName).scm.azurewebsites.net/api/vfs/$LogFilePath/"
Write-Verbose "[$(Get-Date -Format s)] : $functionName : Begin Function.."
}
process {
try {
Write-Verbose "[$(Get-Date -Format s)] : $functionName : Fetching web app details.."
# We need username and password to read the logs, oublishing profile can be used to get the information for it
$webApp = Get-AzWebApp -ResourceGroupName $ResourceGroupName -Name $AppServiceName
[xml]$publishingProfile = Get-AzWebAppPublishingProfile -WebApp $webApp
# connect to SCM
$username = $publishingProfile.publishData.publishProfile[0].userName
$password = $publishingProfile.publishData.publishProfile[0].userPWD
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
# this helps me to get the log files under the http/RawLogs folder then manipulate to get the information
$logFiles = Invoke-RestMethod -Uri $scm -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method GET
# Download only recent files
$logFiles = $logFiles | Where-Object { (Get-Date $_.crtime).Date -eq (Get-Date).Date }
if ($Zip.IsPresent) {
Write-Verbose "[$(Get-Date -Format s)] : $functionName : Downloading files from - $LogFilePath.."
Invoke-RestMethod -Uri $scm.Replace("vfs", "zip") -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method GET -OutFile $ExportPath -ContentType "multipart/form-data"
}
foreach ($file in $logFiles) {
if ((Get-Date $file.crtime).Date -eq (Get-Date).Date) {
Write-Verbose "[$(Get-Date -Format s)] : $functionName : Downloading - $($file.name).."
Invoke-RestMethod -Uri "$scm/$($file.name)" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method GET -OutFile "$ExportPath\$($file.name)" -ContentType "text/plain"
}
}
}
catch {
throw $_
}
}
end {
Write-Verbose "[$(Get-Date -Format s)] : $functionName : End Function.."
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment