Skip to content

Tag: Screen Capture

How to Take a Screenshot with PowerShell

Taking screenshots programmatically can be incredibly useful for automating tasks or creating documentation. PowerShell provides a way to take screenshots using .NET classes. Below is a guide to capturing a screenshot and saving it as a .jpg file.

Capture The Entire Screen

Below is a script that captures the screen and saves it as a .jpg file in C:\Temp\.

# Define the location and file name
$directory = "C:\Temp\"
$filename = "screenshot.jpg"
$filepath = $directory + $filename

# Create a bitmap object
Add-Type -AssemblyName System.Drawing
$bitmap = New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width, [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height)

# Create a graphics object from the bitmap
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)

# Capture the screen
$graphics.CopyFromScreen(0, 0, 0, 0, $bitmap.Size)

# Save the bitmap as a .jpg file
$bitmap.Save($filepath, [System.Drawing.Imaging.ImageFormat]::Jpeg)

# Cleanup
$graphics.Dispose()
$bitmap.Dispose()

Write-Host "Screenshot saved to $filepath"

Capturing a Specific Area

Specify the top-left corner (x, y) and the width and height of the rectangle you want to capture.

$x = 100        # x-coordinate of the top-left corner
$y = 100        # y-coordinate of the top-left corner
$width = 500    # width of the rectangle
$height = 300   # height of the rectangle

Use the coordinates and dimensions defined above in the below script:

$x = 100        # x-coordinate of the top-left corner
$y = 100        # y-coordinate of the top-left corner
$width = 500    # width of the rectangle
$height = 300   # height of the rectangle

# Define the location and file name
$directory = "C:\Temp\"
$filename = "area_screenshot.jpg"
$filepath = $directory + $filename
 
# Create a bitmap object with specified dimensions
Add-Type -AssemblyName System.Drawing
$bitmap = New-Object System.Drawing.Bitmap($width, $height)
 
# Create a graphics object from the bitmap
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
 
# Capture the specified area of the screen
$graphics.CopyFromScreen($x, $y, 0, 0, $bitmap.Size)
 
# Save the bitmap as a .jpg file
$bitmap.Save($filepath, [System.Drawing.Imaging.ImageFormat]::Jpeg)
 
# Cleanup
$graphics.Dispose()
$bitmap.Dispose()
 
Write-Host "Screenshot of the specified area saved to $filepath"

Conclusion

PowerShell provides powerful capabilities for capturing screenshots, whether you need the entire screen, or a specific area. By adjusting the script parameters, you can tailor the screenshot capture process to meet your specific needs.

© 2024 ScriptWizards.net - Powered by Coffee & Magic