Created
June 11, 2024 14:07
-
-
Save nanoDBA/70a3675695b0a918ec8ed2cfc0ff5cd9 to your computer and use it in GitHub Desktop.
Turn off the display and lock the workstation using the Windows API via PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# filename: Lock_and_power_off_display.ps1 | |
# | |
# This script turns off the display and locks the workstation using the Windows API. | |
# | |
# Warning: This script will turn off the display and lock the workstation indefinitely until stopped manually. | |
# | |
# Import the necessary libraries for interacting with the Windows API | |
Add-Type @" | |
using System; | |
using System.Runtime.InteropServices; | |
public class Screen { | |
[DllImport("user32.dll")] public static extern void LockWorkStation(); | |
[DllImport("user32.dll")] public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam); | |
public const int HWND_BROADCAST = 0xFFFF; | |
public const int WM_SYSCOMMAND = 0x0112; | |
public const int SC_MONITORPOWER = 0xF170; | |
public static void PowerOff() { | |
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2); | |
} | |
} | |
"@ | |
# Start a background job with a specific name | |
Start-Job -Name "LockAndPowerOff" -ScriptBlock { | |
# Import the necessary libraries for interacting with the Windows API | |
Add-Type @" | |
using System; | |
using System.Runtime.InteropServices; | |
public class Screen { | |
[DllImport("user32.dll")] public static extern void LockWorkStation(); | |
[DllImport("user32.dll")] public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam); | |
public const int HWND_BROADCAST = 0xFFFF; | |
public const int WM_SYSCOMMAND = 0x0112; | |
public const int SC_MONITORPOWER = 0xF170; | |
public static void PowerOff() { | |
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2); | |
} | |
} | |
"@ | |
# Turn off the display | |
[Screen]::PowerOff() | |
# Wait for 2 seconds | |
Start-Sleep -Seconds 2 | |
# Lock the workstation | |
[Screen]::LockWorkStation() | |
} | Out-Null | |
# Display a message to indicate that the display is turned off and the workstation is locked | |
Write-Host "Display turned off and workstation locked. Press CTRL+C to stop." | |
try { | |
# Keep the script running indefinitely | |
while ($true) { | |
Start-Sleep -Seconds 1 | |
} | |
} catch { | |
# If an exception occurs, stop the background job and exit the script | |
Get-Job -Name "LockAndPowerOff" | Stop-Job -Force | |
Write-Host "Job 'LockAndPowerOff' stopped and script exited." | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment