Skip to content

PowerShell Snippets

Steve Williams edited this page Jan 21, 2023 · 4 revisions

Here are a collection of scripts that I have created over lifetime of Move Mouse in response to feedback. Please feel free to send me any requests for more.

I recommend you use Visual Studio Code to create and edit scripts.

Minimise All Windows (Show Desktop)

$ShellApp = New-Object -ComObject Shell.Application
$ShellApp.MinimizeAll()

Send Keystroke Combination

# A full list of supported keystrokes can be found here:
# http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx
$WshShell = New-Object -ComObject WScript.Shell
$WshShell.SendKeys("^{ESC}")

Lock Session

Start-Process -FilePath "C:\Windows\System32\rundll32.exe" -ArgumentList "user32.dll,LockWorkStation"

Terminate Process

Stop-Process -Name notepad -Force

Start Service

Start-Service -Name MyService

Stop Service

Stop-Service -Name MyService

Restart Service

Restart-Service -Name MyService -Force

Delete File

Remove-Item -Path "C:\My Path\MyFile.ext" -Force

Copy File

Copy-Item -Path "C:\My Path\MyFile.ext" -Destination "C:\Another Path\MyFile.ext" -Force

Move File

Move-Item -Path "C:\My Path\MyFile.ext" -Destination "C:\Another Path\MyFile.ext" -Force

Send Keystroke Combination

# A full list of supported keystrokes can be found here:
# http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx
$WshShell = New-Object -ComObject WScript.Shell
$WshShell.SendKeys("^{ESC}")

Minimise, Maximise and Restore Window

Add-Type -MemberDefinition @"
//[https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow](https://www.google.com/url?q=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fwin32%2Fapi%2Fwinuser%2Fnf-winuser-showwindow&sa=D&sntz=1&usg=AOvVaw1GoRFzdLibOvsmuPa7BbYk)

[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(
    IntPtr hWnd, 
    int nCmdShow);
"@ -Name "NativeMethods" -Namespace "Win32"

$Hwnd = (Get-Process -Name "Notepad")[0].MainWindowHandle # Obtain handle to window
[Win32.NativeMethods]::ShowWindowAsync($Hwnd, 2) # Minimise window
[Win32.NativeMethods]::ShowWindowAsync($Hwnd, 3) # Maximise window
[Win32.NativeMethods]::ShowWindowAsync($Hwnd, 4) # Restore window

Position Window

Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;

public class NativeMethods
{
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetWindowRect(
        IntPtr hWnd,
        out RECT lpRect);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public extern static bool MoveWindow( 
        IntPtr handle,
        int x,
        int y,
        int width,
        int height,
        bool redraw);
}

public struct RECT
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}
"@

$Hwnd = (Get-Process -Name "Move Mouse")[0].MainWindowHandle # Obtain handle to window
$Rect = New-Object RECT # Create empty RECT object that can be used in the GetWindowRect() function
[NativeMethods]::GetWindowRect($Hwnd, [ref]$Rect) # Obtain window positional information
$Width = $Rect.Right - $Rect.Left # Calculate width
$Height = $Rect.Bottom - $Rect.Top # Calculate height
[NativeMethods]::MoveWindow($Hwnd, 500, 500, $Width, $Height, $true) # Move window

Click And Drag Mouse Cursor

Add-Type -TypeDefinition @"
using System;
using System.Threading;
using System.Runtime.InteropServices;

namespace NativeMethods
{
    public static class Mouse
    {
        [DllImport("user32.dll")]
        public static extern void mouse_event(MouseEventFlags dwFlags, int dx, int dy, int dwData, UIntPtr dwExtraInfo);

        [DllImport("User32.dll")]
        public static extern bool SetCursorPos(
            int X,
            int Y);

        [Flags]
        public enum MouseEventFlags
        {
            LEFTDOWN = 0x00000002,
            LEFTUP = 0x00000004,
            MIDDLEDOWN = 0x00000020,
            MIDDLEUP = 0x00000040,
            MOVE = 0x00000001,
            ABSOLUTE = 0x00008000,
            RIGHTDOWN = 0x00000008,
            RIGHTUP = 0x00000010,
            WHEEL = 0x0800
        }

        public static void MouseDown()
        {
            mouse_event(MouseEventFlags.LEFTDOWN, 0, 0, 0, UIntPtr.Zero);
        }

        public static void MouseUp()
        {
            mouse_event(MouseEventFlags.LEFTUP, 0, 0, 0, UIntPtr.Zero);
        }
    }
}
"@

[NativeMethods.Mouse]::SetCursorPos(2007, 29) # Move mouse cursor to starting position
[NativeMethods.Mouse]::MouseDown() # Click left mouse button
[NativeMethods.Mouse]::SetCursorPos(2007, 400) # Move cursor to target location
[NativeMethods.Mouse]::MouseUp() # Release left mouse button

Silently Move Mouse Cursor

Add-Type -TypeDefinition @"
using System;
using System.Drawing;
using System.Threading;
using System.Runtime.InteropServices;

namespace NativeMethods
{
    public static class Mouse
    {
        [Flags]
        public enum Win32Consts
        {
            INPUT_MOUSE = 0,
            INPUT_KEYBOARD = 1,
            INPUT_HARDWARE = 2,
        }

        [Flags]
        public enum MouseEventFlags
        {
            LEFTDOWN = 0x00000002,
            LEFTUP = 0x00000004,
            MIDDLEDOWN = 0x00000020,
            MIDDLEUP = 0x00000040,
            MOVE = 0x00000001,
            ABSOLUTE = 0x00008000,
            RIGHTDOWN = 0x00000008,
            RIGHTUP = 0x00000010,
            WHEEL = 0x00000800,
            HWHEEL = 0x00001000,
            XDOWN = 0x00000080,
            XUP = 0x00000100
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MOUSEINPUT
        {
            public int dx;
            public int dy;
            public int mouseData;
            public MouseEventFlags dwFlags;
            public uint time;
            public UIntPtr dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct INPUT
        {
            public int type;
            public MOUSEINPUT mi;
        }

        [DllImport("user32.dll")]
        public static extern uint SendInput(
            uint nInputs,
            ref INPUT pInputs,
            int cbSize);

        public static void MoveFromCurrentLocation(Point point)
        {
            var mi = new MOUSEINPUT
            {
                dx = point.X,
                dy = point.Y,
                mouseData = 0,
                time = 0,
                dwFlags = MouseEventFlags.MOVE,
                dwExtraInfo = UIntPtr.Zero
            };
            var input = new INPUT
            {
                mi = mi,
                type = Convert.ToInt32(Win32Consts.INPUT_MOUSE)
            };
            SendInput(1, ref input, Marshal.SizeOf(input));
        }
    }
}
"@ -ReferencedAssemblies System.Drawing

# Infinite loop
do {
    [NativeMethods.Mouse]::MoveFromCurrentLocation([System.Drawing.Point]::New(0, 0)) # Silently move mouse cursor
    Start-Sleep -Seconds 30 # Pause for 30 seconds
} while ($true)