ps/Modules/Alkami.DevOps.TeamCity/Public/Get-EC2ConsoleSnapshot.ps1

72 lines
2.5 KiB
PowerShell
Raw Permalink Normal View History

2023-05-30 22:51:22 -07:00
function Get-EC2ConsoleSnapshot {
<#
.SYNOPSIS
Returns an AWS instance console screenshot .jpg to the user's download folder
.PARAMETER ComputerName
Hostname(s) of a machine that is located in AWS
.PARAMETER InstanceId
AWS owned ID(s) of a machine
.PARAMETER ProfileName
AWS environment credential
.PARAMETER Type
Optional Parameter. Type of TeamCity host(s) to return: All, Server(s), or Agent(s)
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[string[]]$ComputerName,
[Parameter(Mandatory = $false)]
[string[]]$InstanceId,
[Parameter(Mandatory = $true)]
[string]$ProfileName,
[ValidateSet("All", "Server", "Agent")]
[Parameter(Mandatory = $false)]
[string]$Type
)
$logLead = Get-LogLeadName
if (!(Test-StringIsNullOrWhitespace -Value $Type)) {
$ComputerName = Get-TeamCityHostnames -Type $Type -ProfileName $ProfileName
}
if ((Test-IsCollectionNullOrEmpty -Collection $ComputerName) -and (Test-IsCollectionNullOrEmpty -Collection $InstanceId)) {
Write-Warning "$loglead : A ComputerName or InstanceId was not provided, exiting..."
Return
}
if (Test-IsCollectionNullOrEmpty -Collection $ComputerName) {
$ComputerName = $InstanceId
}
foreach ($name in $ComputerName) {
if (Test-IsCollectionNullOrEmpty -Collection $InstanceId) {
$hostnameInstanceId = (Get-EC2InstancesByHostname -ProfileName $ProfileName -Servers $name).InstanceId
} else {
$hostnameInstanceId = $name
}
try {
Write-Verbose "$loglead : Attempting Region : us-east-1"
$image = Get-EC2ConsoleScreenshot -InstanceId $hostnameInstanceId -ProfileName $ProfileName -Region "us-east-1"
} catch [InvalidOperationException] {
Write-Verbose "$loglead : Attempting Region : us-west-2"
$image = Get-EC2ConsoleScreenshot -InstanceId $hostnameInstanceId -ProfileName $ProfileName -Region "us-west-2"
} catch {
Write-Host "$($_.Exception.Message)"
}
$imageData = [Convert]::FromBase64String($image.ImageData)
$datetime = Get-Date -Format "MM_dd_yyyy_HHmm"
$outFile = "$env:USERPROFILE\Downloads\$($name)_$($datetime).jpg"
Write-Host "$loglead : Writing image file to $outFile"
try {
[IO.File]::WriteAllBytes($outFile, $imageData)
} catch {
Write-Error "$logLead : $_"
}
}
}