Facebook
From none, 2 Days ago, written in VBScript.
Embed
Download Paste or View Raw
Hits: 42
  1. ' Date: 2025-06-26
  2. ' Version: 1.0.0
  3. ' License: MIT License
  4. '
  5. ' Copyright (c) 2025
  6. '
  7. ' Permission is hereby granted, free of charge, to any person obtaining a copy
  8. ' of this software and associated documentation files (the "Software"), to deal
  9. ' in the Software without restriction, including without limitation the rights
  10. ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. ' copies of the Software, and to permit persons to whom the Software is
  12. ' furnished to do so, subject to the following conditions:
  13. '
  14. ' The above copyright notice and this permission notice shall be included in all
  15. ' copies or substantial portions of the Software.
  16. '
  17. ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. ' SOFTWARE.
  24.  
  25.  
  26. ' Description:
  27. ' This VBScript is a wrapper to launch a PowerShell script that installs/is a watcher for exiting SolidWorks.
  28. ' It creates a Scheduled Task that runs watcher script at user logon, which activates once SolidWorks is closed.
  29. ' The watcher script will automatically deactivate the license.
  30.  
  31. ' It takes a few seconds to detect the shutdown.
  32. ' The Activation Wizard will be left on the "Deactivation Successful" page afterwards, so the user can use this as license deactivation confirmation.
  33.  
  34. ' This will not run if Windows is being shut down/crashing while SolidWorks is running however!
  35.  
  36. ' Usage:
  37. ' Double-click the VBScript file to run it.
  38. ' It will prompt for the main SOLIDWORKS Corp installation folder. Copy paste this.
  39. ' Edit pollSeconds and windowDelay in SWActivationWatcher.ps1 if on a slow computer or if you want to speed up the process (then reboot).
  40.  
  41.  
  42.  
  43. Set objShell = CreateObject("Shell.Application")
  44. ' Create the PowerShell script alongside the VBScript if it doesn't exist
  45. Set fso = CreateObject("Scripting.FileSystemObject")
  46. ' Determine the PowerShell script path based on this VBScript’s folder
  47. Dim scriptFolder
  48. scriptFolder = fso.GetParentFolderName(WScript.ScriptFullName)
  49. psPath = scriptFolder & "\SWActivationWatcher.ps1"
  50. If Not fso.FileExists(psPath) Then
  51.     Set file = fso.CreateTextFile(psPath, True)
  52.  file.WriteLine "#Requires -RunAsAdministrator"
  53.  file.WriteLine "<#"
  54.  file.WriteLine ".SYNOPSIS"
  55.  file.WriteLine "    Installs and runs a watcher to automatically handle the SolidWorks activation prompt on close."
  56.  file.WriteLine "    This script is self-relocating and designed to be launched by an admin batch file."
  57.  file.WriteLine ""
  58.  file.WriteLine ".DESCRIPTION"
  59.  file.WriteLine "    INSTALLER MODE:"
  60.  file.WriteLine "    - Asks for the main SOLIDWORKS Corp installation folder."
  61.  file.WriteLine "    - Creates a 'Scripts' subfolder inside the SOLIDWORKS Corp directory."
  62.  file.WriteLine "    - Copies itself to this new, permanent location."
  63.  file.WriteLine "    - Creates a Scheduled Task that runs the *copied* script at user logon."
  64.  file.WriteLine "    - Starts the Scheduled Task immediately after creation."
  65.  file.WriteLine ""
  66.  file.WriteLine "    WATCHER MODE (Executed by the Scheduled Task):"
  67.  file.WriteLine "    - Runs silently in the background, monitoring for the SolidWorks process to close."
  68.  file.WriteLine "#>"
  69.  file.WriteLine "[CmdletBinding()]"
  70.  file.WriteLine "param ("
  71.  file.WriteLine "    [string]$RunWatcherWithActivatorPath"
  72.  file.WriteLine ")"
  73.  file.WriteLine ""
  74.  file.WriteLine "# Configuration Parameters"
  75.  file.WriteLine "$pollSeconds     = 5   # How often to check if SolidWorks is running"
  76.  file.WriteLine "$windowDelay     = 3   # How long to wait for the activation wizard window to appear"
  77.  file.WriteLine ""
  78.  file.WriteLine "# --- WATCHER MODE ---"
  79.  file.WriteLine "if (-not [string]::IsNullOrEmpty($RunWatcherWithActivatorPath)) {"
  80.  file.WriteLine "    Add-Type -AssemblyName System.Windows.Forms -ErrorAction SilentlyContinue"
  81.  file.WriteLine "    Add-Type -TypeDefinition @"""
  82.  file.WriteLine "    using System;"
  83.  file.WriteLine "    using System.Runtime.InteropServices;"
  84.  file.WriteLine "    public static class NativeMethods {"
  85.  file.WriteLine "        [DllImport(""user32.dll"", SetLastError = false)]"
  86.  file.WriteLine "        public static extern bool SetForegroundWindow(IntPtr hWnd);"
  87.  file.WriteLine ""
  88.  file.WriteLine "        [DllImport(""user32.dll"", SetLastError = true, CharSet = CharSet.Auto)]"
  89.  file.WriteLine "        public static extern IntPtr FindWindowEx("
  90.  file.WriteLine "            IntPtr hwndParent,"
  91.  file.WriteLine "            IntPtr hwndChildAfter,"
  92.  file.WriteLine "            string lpszClass,"
  93.  file.WriteLine "            string lpszWindow);"
  94.  file.WriteLine ""
  95.  file.WriteLine "        [DllImport(""user32.dll"", CharSet = CharSet.Auto)]"
  96.  file.WriteLine "        public static extern IntPtr SendMessage("
  97.  file.WriteLine "            IntPtr hWnd,"
  98.  file.WriteLine "            uint Msg,"
  99.  file.WriteLine "            IntPtr wParam,"
  100.  file.WriteLine "            IntPtr lParam);"
  101.  file.WriteLine "    }"
  102.  file.WriteLine """@ -ErrorAction SilentlyContinue"
  103.  file.WriteLine ""
  104.  file.WriteLine "    # Constants"
  105.  file.WriteLine "    $BM_CLICK = 0x00F5"
  106.  file.WriteLine "    $swProcessName = 'SLDWORKS'"
  107.  file.WriteLine "    $activationExe = $RunWatcherWithActivatorPath"
  108.  file.WriteLine "    # Log file path"
  109.  file.WriteLine "    $wasRunning      = $false"
  110.  file.WriteLine ""
  111.  file.WriteLine "    if (-not (Test-Path $activationExe)) { exit }"
  112.  file.WriteLine ""
  113.  file.WriteLine "    while ($true) {"
  114.  file.WriteLine "        $running = Get-Process -Name $swProcessName -ErrorAction SilentlyContinue"
  115.  file.WriteLine "        if (-not $running -and $wasRunning) {"
  116.  file.WriteLine "            try {"
  117.  file.WriteLine "                # Launch the GUI wizard"
  118.  file.WriteLine "                $wizProc = Start-Process -FilePath $activationExe -PassThru"
  119.  file.WriteLine "                Start-Sleep -Seconds $windowDelay"
  120.  file.WriteLine ""
  121.  file.WriteLine "                # Bring it to foreground (in case it’s hidden behind)"
  122.  file.WriteLine "                if ($wizProc.MainWindowHandle -ne [IntPtr]::Zero) {"
  123.  file.WriteLine "                    [NativeMethods]::SetForegroundWindow($wizProc.MainWindowHandle) | Out-Null"
  124.  file.WriteLine "                }"
  125.  file.WriteLine ""
  126.  file.WriteLine "                # Find and click “Next >” twice"
  127.  file.WriteLine "                for ($i = 1; $i -le 2; $i++) {"
  128.  file.WriteLine "                    $btn = [NativeMethods]::FindWindowEx("
  129.  file.WriteLine "                        $wizProc.MainWindowHandle,"
  130.  file.WriteLine "                        [IntPtr]::Zero,"
  131.  file.WriteLine "                        ""Button"","
  132.  file.WriteLine "                        ""&Next; >"""
  133.  file.WriteLine "                    )"
  134.  file.WriteLine "                    if ($btn -eq [IntPtr]::Zero) {"
  135.  file.WriteLine "                        throw ""Could not find 'Next >' button on attempt #$i"""
  136.  file.WriteLine "                    }"
  137.  file.WriteLine "                    [NativeMethods]::SendMessage($btn, $BM_CLICK, [IntPtr]::Zero, [IntPtr]::Zero) | Out-Null"
  138.  file.WriteLine "                    Start-Sleep -Milliseconds 100"
  139.  file.WriteLine "                }"
  140.  file.WriteLine "            }"
  141.  file.WriteLine "            catch {"
  142.  file.WriteLine "                Add-Content -Path ""$env:ProgramData\SWActivationWatcher.log"" `"
  143.  file.WriteLine "                    -Value ""$(Get-Date -Format o)  ERROR: $($_.Exception.Message)"""
  144.  file.WriteLine "            }"
  145.  file.WriteLine "        }"
  146.  file.WriteLine ""
  147.  file.WriteLine "        $wasRunning = [bool]$running"
  148.  file.WriteLine "        Start-Sleep -Seconds $pollSeconds"
  149.  file.WriteLine "    }"
  150.  file.WriteLine "    exit"
  151.  file.WriteLine "}"
  152.  file.WriteLine ""
  153.  file.WriteLine "# --- INSTALLER MODE ---"
  154.  file.WriteLine "if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] ""Administrator"")) {"
  155.  file.WriteLine "    Write-Host ""ERROR: This script must be run with Administrator rights."" -ForegroundColor Red"
  156.  file.WriteLine "    Write-Host ""Please run the 'run-installer.bat' file as an Administrator."" -ForegroundColor Yellow"
  157.  file.WriteLine "    Read-Host ""Press Enter to exit"""
  158.  file.WriteLine "    exit"
  159.  file.WriteLine "}"
  160.  file.WriteLine ""
  161.  file.WriteLine "function Write-HostColored { param($Message, $Color); Write-Host $Message -ForegroundColor $Color }"
  162.  file.WriteLine "Clear-Host"
  163.  file.WriteLine "Write-HostColored ""=========================================="" -Color Green"
  164.  file.WriteLine "Write-HostColored "" SolidWorks Activation Watcher Installer"" -Color Green"
  165.  file.WriteLine "Write-HostColored ""=========================================="" -Color Green"
  166.  file.WriteLine "Write-Host """""
  167.  file.WriteLine "Write-HostColored ""Administrator rights detected. Ready to install."" -Color Green"
  168.  file.WriteLine "Write-Host """""
  169.  file.WriteLine ""
  170.  file.WriteLine "$swParentFolder = Read-Host ""Enter path to the main SOLIDWORKS Corp folder (e.g., 'C:\Program Files\SOLIDWORKS Corp')"""
  171.  file.WriteLine "if (-not (Test-Path -Path $swParentFolder -PathType Container)) {"
  172.  file.WriteLine "    Write-HostColored "" ERROR: The folder '$swParentFolder' does not exist."" -Color Red"
  173.  file.WriteLine "    Read-Host ""Press Enter to exit""; exit"
  174.  file.WriteLine "}"
  175.  file.WriteLine ""
  176.  file.WriteLine "$installDir = Join-Path -Path $swParentFolder -ChildPath ""Scripts"""
  177.  file.WriteLine "$installPath = Join-Path -Path $installDir -ChildPath ""SWActivationWatcher.ps1"""
  178.  file.WriteLine "$scriptCurrentPath = $MyInvocation.MyCommand.Path"
  179.  file.WriteLine ""
  180.  file.WriteLine "Write-Host """""
  181.  file.WriteLine "Write-HostColored ""Preparing installation..."" -Color Cyan"
  182.  file.WriteLine "if (-not (Test-Path -Path $installDir)) { New-Item -Path $installDir -ItemType Directory | Out-Null }"
  183.  file.WriteLine "Copy-Item -Path $scriptCurrentPath -Destination $installPath -Force"
  184.  file.WriteLine "Write-Host "" -> Script copied to permanent location: $installPath"""
  185.  file.WriteLine ""
  186.  file.WriteLine "Write-Host "" -> Searching for swactwiz.exe..."""
  187.  file.WriteLine "$activator = Get-ChildItem -Path $swParentFolder -Filter ""swactwiz.exe"" -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1"
  188.  file.WriteLine "if (-not $activator) {"
  189.  file.WriteLine "    Write-HostColored "" ERROR: Could not find swactwiz.exe."" -Color Red"
  190.  file.WriteLine "    Read-Host ""Press Enter to exit""; exit"
  191.  file.WriteLine "}"
  192.  file.WriteLine "$activatorPath = $activator.FullName"
  193.  file.WriteLine "Write-HostColored ""Found activator at: $activatorPath"" -Color Green"
  194.  file.WriteLine ""
  195.  file.WriteLine "Write-Host "" -> Creating Scheduled Task to run on login..."""
  196.  file.WriteLine "$taskName = ""SWActivationWatcher"""
  197.  file.WriteLine "$taskAction = New-ScheduledTaskAction -Execute ""powershell.exe"" -Argument ""-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `""$installPath`"" -RunWatcherWithActivatorPath `""$activatorPath`"""""
  198.  file.WriteLine "$taskTrigger = New-ScheduledTaskTrigger -AtLogOn"
  199.  file.WriteLine "$taskPrincipal = New-ScheduledTaskPrincipal -UserId (whoami) -LogonType Interactive -RunLevel Highest"
  200.  file.WriteLine "Register-ScheduledTask -TaskName $taskName -Action $taskAction -Trigger $taskTrigger -Principal $taskPrincipal -Description ""Monitors for SolidWorks closing and handles the activation prompt."" -Force | Out-Null"
  201.  file.WriteLine ""
  202.  file.WriteLine "# Start the task immediately so the user doesn't have to wait for a reboot."
  203.  file.WriteLine "Write-Host "" -> Starting the watcher task now for the current session..."""
  204.  file.WriteLine "try {"
  205.  file.WriteLine "    Start-ScheduledTask -TaskName $taskName"
  206.  file.WriteLine "    Write-HostColored ""Watcher task is now running in the background."" -Color Green"
  207.  file.WriteLine "} catch {"
  208.  file.WriteLine "    Write-HostColored ""Could not start the task immediately. It will start automatically on the next login."" -Color Yellow"
  209.  file.WriteLine "}"
  210.  file.WriteLine ""
  211.  file.WriteLine "Write-Host """""
  212.  file.WriteLine "Write-HostColored ""Success! Installation is complete."" -Color Green"
  213.  file.WriteLine "Try { Remove-Item -Path $MyInvocation.MyCommand.Path -Force -ErrorAction SilentlyContinue } Catch {}"
  214.  file.WriteLine "Write-Host """""
  215.  file.WriteLine "Write-Host ""The installed task script is located at:"""
  216.  file.WriteLine "Write-Host $installPath -ForegroundColor White"
  217.  file.Close
  218. End If
  219.  
  220. ' Launch PowerShell as administrator and bypass execution policy, run via cmd.exe with /k to keep console open
  221. objShell.ShellExecute "cmd.exe", "/k powershell.exe -NoProfile -ExecutionPolicy Bypass -File """ & psPath & """", "", "runas", 1
captcha