Functions/Scraping/Invoke-Screenshot.ps1

function Invoke-Screenshot
    {
    [CmdletBinding(DefaultParameterSetName='Memory')]
    Param
        (
        [Parameter(Mandatory=$false)]
        [ValidateSet("Default","Prompt")]
        [string]
        $BoundSetting = "Default",
        
        [Parameter(Mandatory=$false,ParameterSetName='File')]
        [switch]
        $ToFile,

        [Parameter(Mandatory=$false,ParameterSetName='File')]
        [string]
        $Path
        )

    Process
        {
        # Load Drawing Assembly
        [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")

        # Establish Bounds Based on Setting
        Switch ($BoundSetting)
            {
            "Default"
                {
                $Screen = Get-WmiObject -Class Win32_DesktopMonitor | Select-Object ScreenWidth,ScreenHeight
                $X = 0
                $Y = 0
                $W = $Screen.ScreenWidth[1]
                $H = $Screen.ScreenHeight[1]
                }
            "Prompt"
                {
                $X = Read-Host -Prompt "Capture X Origin?"
                $Y = Read-Host -Prompt "Capture Y Origin?"
                $W = Read-Host -Prompt "Capture Width?"
                $H = Read-Host -Prompt "Capture Height?"
                }
            }
        $Bounds = [Drawing.Rectangle]::new($X,$Y,$W,$H)

        # Determine Output Type from Parameter Input
        $OutputType = $PSCmdlet.ParameterSetName

        # Map Path if it exists
        if ($OutputType -eq "File" -and !$Path){$Path = Select-SaveFilePath -FileName ".png"}

        # Create a Bitmap object and copy screen pixels into it
        $bmp = New-Object Drawing.Bitmap $bounds.width, $bounds.height
        $graphics = [Drawing.Graphics]::FromImage($bmp)
        $graphics.CopyFromScreen($bounds.Location, [Drawing.Point]::Empty, $bounds.size)

        # Output based on Output Type
        switch ($OutputType)
            {
            "Memory"
                {
                $Stream = New-Object System.IO.MemoryStream
                $bmp.Save($stream,'Png')
                $Stream.ToArray()
                }
            "File"
                {
                $bmp.Save($path)
                Write-Host "HTML Captured to $Path" -ForegroundColor Cyan
                }
            }

        # Dispose of Objects
        if($stream){$stream.Dispose()}
        if($graphics){$graphics.Dispose()}
        if($bmp){$bmp.Dispose()}
        }
    }