powershellscreenshotps1

Take a screenshot of each screen separately


I'm trying take a screenshot of each of my screens.

Unfortunately, after searching for hours, I've found nothing.

Here is my actual PowerShell script content :

Add-Type -AssemblyName System.Windows.Forms,System.Drawing 
$screens = [Windows.Forms.Screen]::AllScreens 
$top    = ($screens.Bounds.Top    ^| Measure-Object -Minimum).Minimum 
$left   = ($screens.Bounds.Left   ^| Measure-Object -Minimum).Minimum 
$width  = ($screens.Bounds.Right  ^| Measure-Object -Maximum).Maximum 
$height = ($screens.Bounds.Bottom ^| Measure-Object -Maximum).Maximum 
$bounds   = [Drawing.Rectangle]::FromLTRB($left, $top, $width, $height) 
$bmp      = New-Object System.Drawing.Bitmap ([int]$bounds.width), ([int]$bounds.height) 
$graphics = [Drawing.Graphics]::FromImage($bmp) 
$graphics.CopyFromScreen($bounds.Location, [Drawing.Point]::Empty, $bounds.size) 
$bmp.Save("%path%\tmp\Screenshots\%1.png") 
$graphics.Dispose() 
$bmp.Dispose() 
%powershell% -ExecutionPolicy Bypass -File "%path%\librairies\sg.ps1"

This takes a screenshot of all of my screens but in one file, what I would like is to detect the number of screens, and take screenshot of each, for example files named : Screen1.png, Screen2.png, etc...


Solution

  • Loop over each screen returned by [Windows.Forms.Screen]::AllScreen:

    Add-Type -AssemblyName System.Windows.Forms,System.Drawing 
    
    foreach ($screen in [Windows.Forms.Screen]::AllScreens) {
        $bounds   = $screen.Bounds
        try {
            $bmp      = New-Object System.Drawing.Bitmap ([int]$bounds.Width), ([int]$bounds.Height) 
            $graphics = [Drawing.Graphics]::FromImage($bmp) 
            $graphics.CopyFromScreen($bounds.Location, [Drawing.Point]::Empty, $bounds.Size) 
            $screenName = $screen.DeviceName -replace '^.*\\([^\\]+)$'
            $bmp.Save("$env:PATH\tmp\Screenshots\$screenName.png")
        }
        finally {
            $graphics.Dispose() 
            $bmp.Dispose() 
        }
    }