Script Examples

Simply copy and paste any of the snippets below into your custom scripts to start automating!

Please feel free to contact me if you have any ideas for snippets that could be made available on this page.

PowerShell Snippets

Launch an application/process
Start-Process -FilePath "C:\Windows\notepad.exe" -WindowStyle Normal -Wait:$false

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 screen
Start-Process -FilePath "C:\Windows\System32\rundll32.exe" -ArgumentList "user32.dll,LockWorkStation"

Terminate a process
Stop-Process -Name notepad -Force

Start a service
Start-Service -Name MyService

Stop a service
Stop-Service -Name MyService

Restart a service
Restart-Service -Name MyService -Force

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

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

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

Active at specific times of day/week
I was asked if Move Mouse could only be active at certain times of the week (Mon-Fri 9:00am-5:00pm). This can be achieved using the following code that must be configured as an Interval script.
$SendShiftKey = $false

if (((Get-Date).Hour -ge 9) -and ((Get-Date).Hour -lt 17)) {
    switch ((Get-Date).DayOfWeek) {
        Monday {
            $SendShiftKey = $true
        }
        Tuesday {
            $SendShiftKey = $true
        }
        Wednesday {
            $SendShiftKey = $true
        }
        Thursday {
            $SendShiftKey = $true
        }
        Friday {
            $SendShiftKey = $true
        }
    }
}

if ($SendShiftKey) {
    Write-Host "Sending shift key..."
    $WshShell = New-Object -ComObject "WScript.Shell"
    $WshShell.SendKeys("+")
}

Simulate mouse movement and click
I was asked if Move Mouse could move the mouse pointer to specific coordinates on screen, and send a left-click or right-click.
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$MouseEventSig=@' 
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
'@ 
$MouseEvent = Add-Type -memberDefinition $MouseEventSig -name "MouseEventWinApi" -passThru
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(100,100)
$MouseEvent::mouse_event(0x00000002, 0, 0, 0, 0);
$MouseEvent::mouse_event(0x00000004, 0, 0, 0, 0);
Start-Sleep -Milliseconds 500
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(200,200)
$MouseEvent::mouse_event(0x00000002, 0, 0, 0, 0);
$MouseEvent::mouse_event(0x00000004, 0, 0, 0, 0);
Start-Sleep -Milliseconds 500
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(300,300)
$MouseEvent::mouse_event(0x00000008, 0, 0, 0, 0);
$MouseEvent::mouse_event(0x00000010, 0, 0, 0, 0);

Randomised Interval
I was asked if Move Mouse's interval could be randomised.
$LowerSeconds = 30
$UpperSeconds = 40
$MoveMouseXml = Join-Path $env:APPDATA "Ellanet\Move Mouse\Move Mouse.xml"

if (Test-Path -Path $MoveMouseXml) {
    $XmlDoc = New-Object System.Xml.XmlDocument
    $XmlDoc.Load($MoveMouseXml)
    $XmlDoc.SelectSingleNode("settings/second_delay").InnerText = Get-Random -Minimum $LowerSeconds -Maximum $UpperSeconds
    $XmlDoc.Save($MoveMouseXml)
}

Randomised Blackout schedules
I was asked if Move Mouse could randomise the Blackout schedules.
$MoveMouseXml = Join-Path $env:APPDATA "Ellanet\Move Mouse\Move Mouse.xml"

if (Test-Path -Path $MoveMouseXml) {
    $RandomBlackoutStartTime = (Get-Date -Hour 18 -Minute 0).AddSeconds((Get-Random -Minimum 0 -Maximum (New-TimeSpan -Minutes 60).TotalSeconds))
    $RandomBlackoutEndTime = (Get-Date -Hour 9 -Minute 0).AddSeconds((Get-Random -Minimum 0 -Maximum (New-TimeSpan -Minutes 60).TotalSeconds))
    $XmlDoc = New-Object System.Xml.XmlDocument
    $XmlDoc.Load($MoveMouseXml)
    $XmlDoc.SelectSingleNode("settings/blackouts").RemoveAll()
    $BlackoutNode = $XmlDoc.CreateElement("blackout")
    $BlackoutNode.InnerXml = "<start/><end/>"
    $BlackoutNode.SelectSingleNode("start").InnerText = $RandomBlackoutStartTime.ToString("HH:mm:ss")
    $BlackoutNode.SelectSingleNode("end").InnerText = $RandomBlackoutEndTime.ToString("HH:mm:ss")
    $XmlDoc.SelectSingleNode("settings/blackouts").AppendChild($BlackoutNode)
    $XmlDoc.Save($MoveMouseXml)
}

Holding a key
I was asked if it was possible to hold a keystroke from a script.
$KeybdEventSignature = @"
[DllImport("user32.dll")]                                                            
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
"@
$KeybdEvent = Add-Type -memberDefinition $KeybdEventSignature -Name WinApi -passThru
# Press left shift key down
$KeybdEvent::keybd_event([System.Windows.Forms.Keys]::X, 0x45, 0, 0);
Start-Sleep -Seconds 5
# Release left shift key down
$KeybdEvent::keybd_event([System.Windows.Forms.Keys]::X, 0x45, 0x2, 0);

Sporadic mouse movement
I was asked if it was possible to make the mouse movements more random/human like. This isn't perfect as the mouse will always move in a straight line, but it's on the right path.
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Speed = 50 # higher = slower
$Movements = 3

for ($I = 0; $I -lt $Movements; $I++) {
    $XIncrement = ((Get-Random -Minimum 0 -Maximum ([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width)) - [System.Windows.Forms.Cursor]::Position.X) / $Speed
    $YIncrement = ((Get-Random -Minimum 0 -Maximum ([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height)) - [System.Windows.Forms.Cursor]::Position.Y) / $Speed
    $XPos = [System.Windows.Forms.Cursor]::Position.X
    $YPos = [System.Windows.Forms.Cursor]::Position.Y

    for ($J = 0; $J -lt $Speed; $J++) {
        $XPos += $XIncrement
        $YPos += $YIncrement
        [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($XPos, $YPos)
        Start-Sleep -Milliseconds 1
    }
}

VB Script Snippets

Launch an application/process
Const CommandLine = "C:\Temp\MyCustomApp.exe"
Dim wshShell : Set wshShell = CreateObject("WScript.Shell")
wshShell.Run CommandLine, 1, False
Set wshShell = Nothing

Launch a PowerShell script
Const PowerShellScript = "C:\Temp\Script.ps1"
Const PowerShellPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
Dim fsObject : Set fsObject = CreateObject("Scripting.FileSystemObject")

If fsObject.FileExists(PowerShellPath) And fsObject.FileExists(PowerShellScript) Then
    Dim wshShell : Set wshShell = CreateObject("WScript.Shell")
    wshShell.Run """" & PowerShellPath & """ -File """ & PowerShellScript & """" , 1, False
    Set wshShell = Nothing
End If

Set fsObject = Nothing

Minimise all windows (show desktop)
Dim shellApp : Set shellApp = CreateObject("Shell.Application")
shellApp.MinimizeAll()
Set shellApp = Nothing

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
Dim wshShell : Set wshShell = CreateObject("WScript.Shell")
wshShell.SendKeys("^{ESC}") 'CTRL+ESC
Set wshShell = Nothing

Lock screen
Dim wshShell : Set wshShell = CreateObject("WScript.Shell")
wshShell.Run "rundll32.exe user32.dll,LockWorkStation", 1, False
Set wshShell = Nothing

Terminate a process
Const ProcessName = "notepad.exe"
Dim wmiObj : Set wmiObj = CreateObject("WbemScripting.SWbemLocator")
Dim wmiServer : Set wmiServer = wmiObj.ConnectServer()
Dim wmiQuery : Set wmiQuery = wmiServer.InstancesOf("Win32_Process WHERE Name='" & ProcessName & "'")
Dim wmiInst

If wmiQuery.Count > 0 Then

    For Each wmiInst In wmiQuery
        wmiInst.Terminate()
    Next
    
End If

Set wmiQuery = Nothing
Set wmiServer = Nothing
Set wmiObj = Nothing

Last edited Oct 13, 2015 at 3:23 PM by sw3103, version 42

Comments

mosed1 Oct 20, 2015 at 12:39 PM 
Before you can run your scripts you have to activate it in Powershell.
1. Run Powershell as Administrator.
2. Tip "set-ExecutionPolicy"
3.make "RemoteSigned" activ.

Thx for thes axaple scripts