Getting Screen Resolution and Scaling Factor with PowerShell
This blog post will explore a PowerShell script that retrieves the screen resolution and scaling factor of your computer. The script uses a combination of .NET and WMI to gather this information.
Prerequisites
The Script
The script starts by defining a custom .NET class using the `Add-Type` cmdlet. This class, called `ScreenScaling`, uses P/Invoke to import functions from user32.dll and gdi32.dll.
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class ScreenScaling {
[DllImport("user32.dll")]
static extern IntPtr GetDC(IntPtr ptr);
[DllImport("gdi32.dll")]
static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
[DllImport("user32.dll", EntryPoint="ReleaseDC")]
static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDc);
const int LOGPIXELSX = 88;
const int LOGPIXELSY = 90;
public static double GetScalingFactor()
{
IntPtr desktop = GetDC(IntPtr.Zero);
int dpiX = GetDeviceCaps(desktop, LOGPIXELSX);
ReleaseDC(IntPtr.Zero, desktop);
return dpiX / 96.0;
}
}
"@
How It Works
Getting the Scaling Factor
The script uses the `GetScalingFactor()` method of the `ScreenScaling` class to calculate the scaling factor of your screen. This is done by calling the `GetDC()` function to get a handle on the desktop, then using the `GetDeviceCaps()` function to retrieve the DPI (dots per inch) value for the X axis. The DPI value is then divided by 96 to convert it to a scaling percentage.
Getting Monitor Details
The script uses WMI to query the Win32_VideoController class and retrieve the current horizontal and vertical resolution of your monitor. This information, along with the scaling factor, is stored in a custom object.
$res = Get-WmiObject Win32_VideoController | Select-Object CurrentHorizontalResolution, CurrentVerticalResolution
$monitordetails = @(
[PSCustomObject]@{
Horizontal = $res.CurrentHorizontalResolution
Vertical = $res.CurrentVerticalResolution
Scaling = $scalingPercentage
}
)
Key Code Snippets
$scalingFactor = [ScreenScaling]::GetScalingFactor()
$scalingPercentage = [math]::Round($scalingFactor * 100)
$scalingPercentage
$monitordetails
Usage Examples
To use this script, simply copy and paste it into your PowerShell console. The script will output the scaling factor of your screen as a percentage, along with the current horizontal and vertical resolution of your monitor.
Conclusion
This blog post has demonstrated how to use PowerShell to retrieve the screen resolution and scaling factor of your computer. By combining .NET and WMI, you can gather this information and use it in your scripts or applications.