create_desktop_shortcut.ps1
|
<#PSScriptInfo
.VERSION 1.1.0 .GUID 5991d012-5e7c-4ad2-8ccf-cdb75a0fdc73 .AUTHOR waresoft .COMPANYNAME .COPYRIGHT .TAGS PowerShell Automation .LICENSEURI .PROJECTURI .ICONURI .EXTERNALMODULEDEPENDENCIES .REQUIREDSCRIPTS .EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES v1.1.0: - Hid the PowerShell console window when running this utility via hidden relaunch flags and Win32 ShowWindow fallback. - Added a "Hidden" option to the Window dropdown to create shortcuts that execute target scripts with -WindowStyle Hidden (and start minimized to prevent window flash). - Automatically disables -NoExit when "Hidden" is selected to prevent orphaned background PowerShell processes. - Updated the live command preview to reflect -WindowStyle Hidden dynamically. .PRIVATEDATA #> <# .DESCRIPTION This script makes it easy to create a desktop icon for a powershell script so that it will execute with powershell, including running completely hidden in the background. #> <# .SYNOPSIS GUI Utility to Create Desktop Shortcuts for PowerShell Scripts (Dark Mode + Auto-Elevating + Windowless) .DESCRIPTION Self-elevates to Administrator in STA mode with its own console window hidden, automatically matches Windows 11 Dark/Light mode (with an in-app toggle), lets you browse for a .ps1 script, choose and preview a custom icon (.ico/.exe/.dll), configure PowerShell launch flags (including Hidden window execution), preview the exact command, and save the resulting .lnk shortcut directly to the Desktop. #> # ======================================================================= # AUTO-ELEVATION, STA APARTMENT & HIDDEN CONSOLE CHECK # ======================================================================= $currentPrincipal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent() $isAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) $isSTA = ([Threading.Thread]::CurrentThread.GetApartmentState() -eq 'STA') if (-not $isAdmin) { Start-Process -FilePath 'powershell.exe' -ArgumentList "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -STA -File `"$PSCommandPath`"" -Verb RunAs -WindowStyle Hidden exit } elseif (-not $isSTA) { Start-Process -FilePath 'powershell.exe' -ArgumentList "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -STA -File `"$PSCommandPath`"" -WindowStyle Hidden exit } Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing [System.Windows.Forms.Application]::EnableVisualStyles() # Win32 helpers for Console Hiding, DWM Dark Title Bar, Cue Banners, Shell Icon Picker, and Icon Extraction if (-not ([System.Management.Automation.PSTypeName]'Win32ShellHelper').Type) { Add-Type -ReferencedAssemblies 'System.Drawing' -TypeDefinition @" using System; using System.Drawing; using System.IO; using System.Runtime.InteropServices; using System.Text; public static class Win32ShellHelper { [DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); public static void HideConsoleWindow() { IntPtr hwnd = GetConsoleWindow(); if (hwnd != IntPtr.Zero) { ShowWindow(hwnd, 0); // 0 = SW_HIDE } } [DllImport("dwmapi.dll", PreserveSig = true)] public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize); public static void SetDarkTitleBar(IntPtr hwnd, bool enabled) { if (hwnd == IntPtr.Zero) return; int val = enabled ? 1 : 0; // 20 = DWMWA_USE_IMMERSIVE_DARK_MODE (Win10 20H1+ & Win11), 19 = older Win10 builds if (DwmSetWindowAttribute(hwnd, 20, ref val, sizeof(int)) != 0) { DwmSetWindowAttribute(hwnd, 19, ref val, sizeof(int)); } } [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, string lParam); [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int PickIconDlg(IntPtr hwndOwner, StringBuilder lpstrFile, int nMaxFile, ref int lpdwIconIndex); [DllImport("shell32.dll", CharSet = CharSet.Unicode)] public static extern uint ExtractIconEx(string lpszFile, int nIconIndex, IntPtr[] phiconLarge, IntPtr[] phiconSmall, uint nIcons); [DllImport("user32.dll", SetLastError = true)] public static extern bool DestroyIcon(IntPtr hIcon); public static Bitmap GetIconBitmap(string filePath, int index) { if (string.IsNullOrWhiteSpace(filePath)) return null; string expanded = Environment.ExpandEnvironmentVariables(filePath.Trim().Trim('"')); if (!File.Exists(expanded)) return null; IntPtr[] large = new IntPtr[1]; IntPtr[] small = new IntPtr[1]; uint count = ExtractIconEx(expanded, index, large, small, 1); if (count > 0 && large[0] != IntPtr.Zero) { try { using (Icon ico = Icon.FromHandle(large[0])) { return ico.ToBitmap(); } } finally { DestroyIcon(large[0]); if (small[0] != IntPtr.Zero) DestroyIcon(small[0]); } } if (small[0] != IntPtr.Zero) DestroyIcon(small[0]); if (expanded.EndsWith(".ico", StringComparison.OrdinalIgnoreCase)) { try { using (Icon ico = new Icon(expanded, 32, 32)) { return ico.ToBitmap(); } } catch { } } return null; } } "@ } # Ensure the hosting console window is hidden even if launched from an already-elevated STA session [Win32ShellHelper]::HideConsoleWindow() $psExePath = Join-Path -Path $env:SystemRoot -ChildPath 'System32\WindowsPowerShell\v1.0\powershell.exe' $defaultIconSpec = "$psExePath,0" $desktopPath = [Environment]::GetFolderPath('Desktop') # Detect Windows App Theme (0 = Dark Mode, 1 = Light Mode) function Get-SystemDarkMode { try { $val = (Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' -Name 'AppsUseLightTheme' -ErrorAction Stop).AppsUseLightTheme return ($val -eq 0) } catch { return $true } } $script:IsDarkMode = Get-SystemDarkMode $script:StatusKind = 'Neutral' $script:Themes = @{ Dark = @{ FormBg = [System.Drawing.Color]::FromArgb(15, 23, 42) HeaderBg = [System.Drawing.Color]::FromArgb(9, 14, 26) Accent = [System.Drawing.Color]::FromArgb(56, 189, 248) PrimaryBtn = [System.Drawing.Color]::FromArgb(2, 132, 199) SecBtnBg = [System.Drawing.Color]::FromArgb(30, 41, 59) SecBtnBorder = [System.Drawing.Color]::FromArgb(71, 85, 105) InputBg = [System.Drawing.Color]::FromArgb(30, 41, 59) PreviewBg = [System.Drawing.Color]::FromArgb(22, 32, 50) PreviewFg = [System.Drawing.Color]::FromArgb(186, 230, 253) TextPrimary = [System.Drawing.Color]::FromArgb(241, 245, 249) TextMuted = [System.Drawing.Color]::FromArgb(148, 163, 184) GroupTitle = [System.Drawing.Color]::FromArgb(56, 189, 248) Border = [System.Drawing.Color]::FromArgb(51, 65, 85) SuccessText = [System.Drawing.Color]::FromArgb(74, 222, 128) ErrorText = [System.Drawing.Color]::FromArgb(248, 113, 113) } Light = @{ FormBg = [System.Drawing.Color]::FromArgb(248, 250, 252) HeaderBg = [System.Drawing.Color]::FromArgb(15, 23, 42) Accent = [System.Drawing.Color]::FromArgb(56, 189, 248) PrimaryBtn = [System.Drawing.Color]::FromArgb(2, 132, 199) SecBtnBg = [System.Drawing.Color]::FromArgb(226, 232, 240) SecBtnBorder = [System.Drawing.Color]::FromArgb(148, 163, 184) InputBg = [System.Drawing.Color]::White PreviewBg = [System.Drawing.Color]::FromArgb(241, 245, 249) PreviewFg = [System.Drawing.Color]::FromArgb(51, 65, 85) TextPrimary = [System.Drawing.Color]::FromArgb(15, 23, 42) TextMuted = [System.Drawing.Color]::FromArgb(100, 116, 139) GroupTitle = [System.Drawing.Color]::FromArgb(2, 132, 199) Border = [System.Drawing.Color]::FromArgb(203, 213, 225) SuccessText = [System.Drawing.Color]::FromArgb(22, 163, 74) ErrorText = [System.Drawing.Color]::FromArgb(220, 38, 38) } } # ======================================================================= # MAIN FORM & HEADER BANNER # ======================================================================= $form = New-Object System.Windows.Forms.Form -Property @{ Text = 'PowerShell Desktop Shortcut Creator (Administrator)' Size = New-Object System.Drawing.Size(580, 576) MinimumSize = New-Object System.Drawing.Size(580, 576) MaximumSize = New-Object System.Drawing.Size(580, 576) StartPosition = 'CenterScreen' FormBorderStyle = 'FixedDialog' MaximizeBox = $false Font = New-Object System.Drawing.Font('Segoe UI', 9.5) } $headerPanel = New-Object System.Windows.Forms.Panel -Property @{ Dock = 'Top' Height = 64 } $accentBar = New-Object System.Windows.Forms.Panel -Property @{ Dock = 'Bottom' Height = 3 } $lblTitle = New-Object System.Windows.Forms.Label -Property @{ Text = 'PowerShell Desktop Shortcut Creator' ForeColor = [System.Drawing.Color]::FromArgb(248, 250, 252) Font = New-Object System.Drawing.Font('Segoe UI Semibold', 12) Location = New-Object System.Drawing.Point(18, 10) AutoSize = $true } $lblSubtitle = New-Object System.Windows.Forms.Label -Property @{ Text = 'Browse to a .ps1 file, pick an icon, and configure how PowerShell runs it.' ForeColor = [System.Drawing.Color]::FromArgb(148, 163, 184) Font = New-Object System.Drawing.Font('Segoe UI', 8.75) Location = New-Object System.Drawing.Point(19, 35) AutoSize = $true } $btnTheme = New-Object System.Windows.Forms.Button -Property @{ Text = 'Light Mode' Location = New-Object System.Drawing.Point(456, 16) Size = New-Object System.Drawing.Size(90, 28) Font = New-Object System.Drawing.Font('Segoe UI', 8.5) FlatStyle = 'Flat' Cursor = [System.Windows.Forms.Cursors]::Hand } $btnTheme.FlatAppearance.BorderSize = 1 $headerPanel.Controls.AddRange(@($lblTitle, $lblSubtitle, $btnTheme, $accentBar)) $form.Controls.Add($headerPanel) # ======================================================================= # 1. TARGET SCRIPT SELECTION # ======================================================================= $lblScript = New-Object System.Windows.Forms.Label -Property @{ Text = 'PowerShell Script (.ps1):' Location = New-Object System.Drawing.Point(20, 78) AutoSize = $true } $txtScriptPath = New-Object System.Windows.Forms.TextBox -Property @{ Location = New-Object System.Drawing.Point(20, 100) Size = New-Object System.Drawing.Size(435, 25) BorderStyle = 'FixedSingle' } $btnBrowse = New-Object System.Windows.Forms.Button -Property @{ Text = 'Browse...' Location = New-Object System.Drawing.Point(463, 99) Size = New-Object System.Drawing.Size(83, 26) FlatStyle = 'Flat' Cursor = [System.Windows.Forms.Cursors]::Hand } $btnBrowse.FlatAppearance.BorderSize = 1 # ======================================================================= # 2. SHORTCUT NAME # ======================================================================= $lblName = New-Object System.Windows.Forms.Label -Property @{ Text = 'Desktop Shortcut Name:' Location = New-Object System.Drawing.Point(20, 134) AutoSize = $true } $txtShortcutName = New-Object System.Windows.Forms.TextBox -Property @{ Location = New-Object System.Drawing.Point(20, 156) Size = New-Object System.Drawing.Size(526, 25) BorderStyle = 'FixedSingle' } # ======================================================================= # 3. CUSTOM ICON PICKER & LIVE PREVIEW # ======================================================================= $lblIcon = New-Object System.Windows.Forms.Label -Property @{ Text = 'Shortcut Icon (.ico, .exe, .dll):' Location = New-Object System.Drawing.Point(20, 190) AutoSize = $true } $pnlIconBox = New-Object System.Windows.Forms.Panel -Property @{ Location = New-Object System.Drawing.Point(20, 212) Size = New-Object System.Drawing.Size(42, 42) BorderStyle = 'FixedSingle' } $picIcon = New-Object System.Windows.Forms.PictureBox -Property @{ Location = New-Object System.Drawing.Point(4, 4) Size = New-Object System.Drawing.Size(32, 32) SizeMode = 'Zoom' } $pnlIconBox.Controls.Add($picIcon) $txtIconPath = New-Object System.Windows.Forms.TextBox -Property @{ Location = New-Object System.Drawing.Point(70, 220) Size = New-Object System.Drawing.Size(314, 25) Text = $defaultIconSpec BorderStyle = 'FixedSingle' } $btnBrowseIcon = New-Object System.Windows.Forms.Button -Property @{ Text = 'Choose Icon...' Location = New-Object System.Drawing.Point(392, 219) Size = New-Object System.Drawing.Size(92, 26) FlatStyle = 'Flat' Cursor = [System.Windows.Forms.Cursors]::Hand } $btnBrowseIcon.FlatAppearance.BorderSize = 1 $btnResetIcon = New-Object System.Windows.Forms.Button -Property @{ Text = 'Reset' Location = New-Object System.Drawing.Point(490, 219) Size = New-Object System.Drawing.Size(56, 26) FlatStyle = 'Flat' Cursor = [System.Windows.Forms.Cursors]::Hand } $btnResetIcon.FlatAppearance.BorderSize = 1 # ======================================================================= # 4. EXECUTION OPTIONS GROUP (CUSTOM-PAINTED FOR CLEAN DARK BORDERS) # ======================================================================= $grpOptions = New-Object System.Windows.Forms.GroupBox -Property @{ Text = 'PowerShell Launch Options' Location = New-Object System.Drawing.Point(20, 266) Size = New-Object System.Drawing.Size(526, 134) } $grpOptions.Add_Paint({ param($sender, $e) $t = if ($script:IsDarkMode) { $script:Themes.Dark } else { $script:Themes.Light } $e.Graphics.Clear($sender.BackColor) $textSize = $e.Graphics.MeasureString($sender.Text, $sender.Font) $topOffset = [int]($textSize.Height / 2) $borderRect = New-Object System.Drawing.Rectangle(0, $topOffset, ($sender.Width - 1), ($sender.Height - $topOffset - 1)) $pen = New-Object System.Drawing.Pen($t.Border) $e.Graphics.DrawRectangle($pen, $borderRect) $pen.Dispose() $textRect = New-Object System.Drawing.Rectangle(10, 0, ([int]$textSize.Width + 6), ([int]$textSize.Height + 2)) $bgBrush = New-Object System.Drawing.SolidBrush($sender.BackColor) $e.Graphics.FillRectangle($bgBrush, $textRect) $bgBrush.Dispose() $fgBrush = New-Object System.Drawing.SolidBrush($t.GroupTitle) $e.Graphics.DrawString($sender.Text, $sender.Font, $fgBrush, 12, 0) $fgBrush.Dispose() }) $chkRunAs = New-Object System.Windows.Forms.CheckBox -Property @{ Text = 'Run as Administrator (UAC prompt on launch)' Location = New-Object System.Drawing.Point(16, 28) AutoSize = $true } $chkNoExit = New-Object System.Windows.Forms.CheckBox -Property @{ Text = 'Keep PowerShell window open after script finishes (-NoExit)' Location = New-Object System.Drawing.Point(16, 54) AutoSize = $true } $chkBypass = New-Object System.Windows.Forms.CheckBox -Property @{ Text = 'Bypass Execution Policy (-ExecutionPolicy Bypass)' Location = New-Object System.Drawing.Point(16, 80) Checked = $true AutoSize = $true } $lblWindow = New-Object System.Windows.Forms.Label -Property @{ Text = 'Window:' Location = New-Object System.Drawing.Point(346, 30) AutoSize = $true } $cmbWindow = New-Object System.Windows.Forms.ComboBox -Property @{ Location = New-Object System.Drawing.Point(404, 26) Size = New-Object System.Drawing.Size(106, 25) DropDownStyle = 'DropDownList' DrawMode = 'OwnerDrawFixed' FlatStyle = 'Flat' ItemHeight = 19 } [void]$cmbWindow.Items.AddRange(@('Normal', 'Minimized', 'Maximized', 'Hidden')) $cmbWindow.SelectedIndex = 0 $cmbWindow.Add_DrawItem({ param($sender, $e) if ($e.Index -lt 0) { return } $t = if ($script:IsDarkMode) { $script:Themes.Dark } else { $script:Themes.Light } $isSelected = ($e.State -band [System.Windows.Forms.DrawItemState]::Selected) -eq [System.Windows.Forms.DrawItemState]::Selected $bgColor = if ($isSelected) { $t.PrimaryBtn } else { $t.InputBg } $fgColor = if ($isSelected) { [System.Drawing.Color]::White } else { $t.TextPrimary } $bgBrush = New-Object System.Drawing.SolidBrush($bgColor) $fgBrush = New-Object System.Drawing.SolidBrush($fgColor) $e.Graphics.FillRectangle($bgBrush, $e.Bounds) $e.Graphics.DrawString($sender.Items[$e.Index].ToString(), $sender.Font, $fgBrush, ($e.Bounds.X + 4), ($e.Bounds.Y + 2)) $bgBrush.Dispose() $fgBrush.Dispose() }) $lblArgs = New-Object System.Windows.Forms.Label -Property @{ Text = 'Script Arguments (optional):' Location = New-Object System.Drawing.Point(16, 106) AutoSize = $true } $txtArgs = New-Object System.Windows.Forms.TextBox -Property @{ Location = New-Object System.Drawing.Point(180, 103) Size = New-Object System.Drawing.Size(330, 23) BorderStyle = 'FixedSingle' } $grpOptions.Controls.AddRange(@( $chkRunAs, $chkNoExit, $chkBypass, $lblWindow, $cmbWindow, $lblArgs, $txtArgs )) # ======================================================================= # 5. LIVE COMMAND PREVIEW & STATUS # ======================================================================= $lblPreview = New-Object System.Windows.Forms.Label -Property @{ Text = 'Shortcut Target Command Preview:' Location = New-Object System.Drawing.Point(20, 410) AutoSize = $true } $txtPreview = New-Object System.Windows.Forms.TextBox -Property @{ Location = New-Object System.Drawing.Point(20, 432) Size = New-Object System.Drawing.Size(526, 42) Multiline = $true ReadOnly = $true BorderStyle = 'FixedSingle' Font = New-Object System.Drawing.Font('Consolas', 8.5) } $lblStatus = New-Object System.Windows.Forms.Label -Property @{ Text = 'Select a PowerShell script to begin.' Location = New-Object System.Drawing.Point(20, 488) Size = New-Object System.Drawing.Size(330, 36) } $btnCreate = New-Object System.Windows.Forms.Button -Property @{ Text = 'Create Shortcut' Location = New-Object System.Drawing.Point(358, 484) Size = New-Object System.Drawing.Size(112, 32) Enabled = $false ForeColor = [System.Drawing.Color]::White FlatStyle = 'Flat' Cursor = [System.Windows.Forms.Cursors]::Hand } $btnCreate.FlatAppearance.BorderSize = 0 $btnClose = New-Object System.Windows.Forms.Button -Property @{ Text = 'Close' Location = New-Object System.Drawing.Point(476, 484) Size = New-Object System.Drawing.Size(70, 32) FlatStyle = 'Flat' Cursor = [System.Windows.Forms.Cursors]::Hand } $btnClose.FlatAppearance.BorderSize = 1 $form.Controls.AddRange(@( $lblScript, $txtScriptPath, $btnBrowse, $lblName, $txtShortcutName, $lblIcon, $pnlIconBox, $txtIconPath, $btnBrowseIcon, $btnResetIcon, $grpOptions, $lblPreview, $txtPreview, $lblStatus, $btnCreate, $btnClose )) # ======================================================================= # THEME ENGINE & HELPER FUNCTIONS # ======================================================================= function Apply-StatusStyle { $t = if ($script:IsDarkMode) { $script:Themes.Dark } else { $script:Themes.Light } $lblStatus.ForeColor = switch ($script:StatusKind) { 'Success' { $t.SuccessText } 'Error' { $t.ErrorText } default { $t.TextMuted } } } function Apply-Theme { $t = if ($script:IsDarkMode) { $script:Themes.Dark } else { $script:Themes.Light } if ($form.IsHandleCreated) { [Win32ShellHelper]::SetDarkTitleBar($form.Handle, $script:IsDarkMode) } $form.BackColor = $t.FormBg $headerPanel.BackColor = $t.HeaderBg $accentBar.BackColor = $t.Accent $btnTheme.Text = if ($script:IsDarkMode) { 'Light Mode' } else { 'Dark Mode' } $btnTheme.BackColor = [System.Drawing.Color]::FromArgb(30, 41, 59) $btnTheme.ForeColor = [System.Drawing.Color]::FromArgb(226, 232, 240) $btnTheme.FlatAppearance.BorderColor = [System.Drawing.Color]::FromArgb(71, 85, 105) foreach ($lbl in @($lblScript, $lblName, $lblIcon, $lblPreview, $lblWindow, $lblArgs)) { $lbl.ForeColor = $t.TextPrimary } foreach ($chk in @($chkRunAs, $chkNoExit, $chkBypass)) { $chk.ForeColor = $t.TextPrimary $chk.BackColor = $t.FormBg } foreach ($tb in @($txtScriptPath, $txtShortcutName, $txtIconPath, $txtArgs)) { $tb.BackColor = $t.InputBg $tb.ForeColor = $t.TextPrimary } $pnlIconBox.BackColor = $t.InputBg $txtPreview.BackColor = $t.PreviewBg $txtPreview.ForeColor = $t.PreviewFg $cmbWindow.BackColor = $t.InputBg $cmbWindow.ForeColor = $t.TextPrimary $cmbWindow.Invalidate() $btnCreate.BackColor = $t.PrimaryBtn $btnCreate.ForeColor = [System.Drawing.Color]::White foreach ($btn in @($btnBrowse, $btnBrowseIcon, $btnResetIcon, $btnClose)) { $btn.BackColor = $t.SecBtnBg $btn.ForeColor = $t.TextPrimary $btn.FlatAppearance.BorderColor = $t.SecBtnBorder } $grpOptions.BackColor = $t.FormBg $grpOptions.Invalidate() Apply-StatusStyle } function Resolve-IconSpec { param([string]$Spec) $raw = if ([string]::IsNullOrWhiteSpace($Spec)) { $defaultIconSpec } else { $Spec.Trim() } $file = $raw $index = 0 if ($raw -match '^(.*),\s*(-?\d+)$') { $file = $Matches[1].Trim().Trim('"') $index = [int]$Matches[2] } else { $file = $raw.Trim('"') } $expanded = [Environment]::ExpandEnvironmentVariables($file) return [PSCustomObject]@{ File = $expanded Index = $index Spec = "$expanded,$index" } } function Update-IconPreview { $parsed = Resolve-IconSpec -Spec $txtIconPath.Text $bmp = [Win32ShellHelper]::GetIconBitmap($parsed.File, $parsed.Index) $oldImg = $picIcon.Image $picIcon.Image = $bmp if ($null -ne $oldImg) { $oldImg.Dispose() } } function Get-PsArgumentString { $parts = [System.Collections.Generic.List[string]]::new() $parts.Add('-NoProfile') if ($chkBypass.Checked) { $parts.Add('-ExecutionPolicy Bypass') } if ($cmbWindow.SelectedItem -eq 'Hidden') { $parts.Add('-WindowStyle Hidden') } if ($chkNoExit.Checked) { $parts.Add('-NoExit') } $target = $txtScriptPath.Text.Trim() if (-not [string]::IsNullOrWhiteSpace($target)) { $parts.Add("-File `"$target`"") } if (-not [string]::IsNullOrWhiteSpace($txtArgs.Text)) { $parts.Add($txtArgs.Text.Trim()) } return ($parts -join ' ') } function Update-FormState { $path = $txtScriptPath.Text.Trim() $isValidFile = (-not [string]::IsNullOrWhiteSpace($path)) -and (Test-Path -LiteralPath $path -PathType Leaf) $btnCreate.Enabled = $isValidFile if ($isValidFile) { $txtPreview.Text = "`"$psExePath`" $(Get-PsArgumentString)" } else { $txtPreview.Text = '' } } # Apply theme immediately before showing, and apply DWM titlebar + cue banner on Shown Apply-Theme $form.Add_Shown({ [Win32ShellHelper]::SetDarkTitleBar($form.Handle, $script:IsDarkMode) [void][Win32ShellHelper]::SendMessage($txtScriptPath.Handle, 0x1501, [IntPtr]1, 'Click Browse to select a .ps1 script...') Update-IconPreview }) $btnTheme.Add_Click({ $script:IsDarkMode = -not $script:IsDarkMode Apply-Theme }) $btnBrowse.Add_Click({ $initDir = $desktopPath $currentText = $txtScriptPath.Text.Trim() if (-not [string]::IsNullOrWhiteSpace($currentText)) { if (Test-Path -LiteralPath $currentText -PathType Container) { $initDir = $currentText } elseif (Test-Path -LiteralPath $currentText -PathType Leaf) { $initDir = Split-Path -Path $currentText -Parent } } $dialog = New-Object System.Windows.Forms.OpenFileDialog -Property @{ Title = 'Select a PowerShell Script (.ps1)' Filter = 'PowerShell Scripts (*.ps1)|*.ps1|All Files (*.*)|*.*' InitialDirectory = $initDir CheckFileExists = $true Multiselect = $false } if ($dialog.ShowDialog($form) -eq [System.Windows.Forms.DialogResult]::OK) { $txtScriptPath.Text = $dialog.FileName $txtShortcutName.Text = [System.IO.Path]::GetFileNameWithoutExtension($dialog.FileName) $script:StatusKind = 'Neutral' $lblStatus.Text = 'Ready to create Desktop shortcut.' Apply-StatusStyle Update-FormState } $dialog.Dispose() }) $btnBrowseIcon.Add_Click({ $parsed = Resolve-IconSpec -Spec $txtIconPath.Text $seedFile = if (Test-Path -LiteralPath $parsed.File -PathType Leaf) { $parsed.File } else { $psExePath } $seedIdx = if (Test-Path -LiteralPath $parsed.File -PathType Leaf) { $parsed.Index } else { 0 } $sb = New-Object System.Text.StringBuilder(260) [void]$sb.Append($seedFile) $iconIndex = [int]$seedIdx $res = [Win32ShellHelper]::PickIconDlg($form.Handle, $sb, $sb.Capacity, [ref]$iconIndex) if ($res -ne 0) { $chosenFile = [Environment]::ExpandEnvironmentVariables($sb.ToString()) $txtIconPath.Text = "$chosenFile,$iconIndex" } }) $btnResetIcon.Add_Click({ $txtIconPath.Text = $defaultIconSpec }) $txtIconPath.Add_TextChanged({ Update-IconPreview }) $txtScriptPath.Add_TextChanged({ Update-FormState }) $chkBypass.Add_CheckedChanged({ Update-FormState }) $chkNoExit.Add_CheckedChanged({ Update-FormState }) $txtArgs.Add_TextChanged({ Update-FormState }) $cmbWindow.Add_SelectedIndexChanged({ if ($cmbWindow.SelectedItem -eq 'Hidden') { $chkNoExit.Checked = $false $chkNoExit.Enabled = $false } else { $chkNoExit.Enabled = $true } Update-FormState }) $btnCreate.Add_Click({ $scriptPath = $txtScriptPath.Text.Trim() if (-not (Test-Path -LiteralPath $scriptPath -PathType Leaf)) { $script:StatusKind = 'Error' $lblStatus.Text = 'Error: The selected script file does not exist.' Apply-StatusStyle return } $iconInfo = Resolve-IconSpec -Spec $txtIconPath.Text if (-not (Test-Path -LiteralPath $iconInfo.File -PathType Leaf)) { $script:StatusKind = 'Error' $lblStatus.Text = 'Error: The selected icon file does not exist.' Apply-StatusStyle return } $rawName = if ([string]::IsNullOrWhiteSpace($txtShortcutName.Text)) { [System.IO.Path]::GetFileNameWithoutExtension($scriptPath) } else { $txtShortcutName.Text.Trim() } $invalidRegex = [Regex]::Escape(([System.IO.Path]::GetInvalidFileNameChars() -join '')) $cleanName = ($rawName -replace "[$invalidRegex]", '').Trim() if ([string]::IsNullOrWhiteSpace($cleanName)) { $cleanName = [System.IO.Path]::GetFileNameWithoutExtension($scriptPath) } $txtShortcutName.Text = $cleanName $shortcutPath = Join-Path -Path $desktopPath -ChildPath "$cleanName.lnk" if (Test-Path -LiteralPath $shortcutPath) { $overwrite = [System.Windows.Forms.MessageBox]::Show( $form, "A shortcut named '$cleanName.lnk' already exists on your Desktop.`n`nDo you want to overwrite it?", 'Confirm Overwrite', [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Question ) if ($overwrite -ne [System.Windows.Forms.DialogResult]::Yes) { return } } try { $wshShell = New-Object -ComObject WScript.Shell $shortcut = $wshShell.CreateShortcut($shortcutPath) $shortcut.TargetPath = $psExePath $shortcut.Arguments = Get-PsArgumentString $shortcut.WorkingDirectory = Split-Path -Path $scriptPath -Parent $shortcut.IconLocation = $iconInfo.Spec $shortcut.WindowStyle = switch ($cmbWindow.SelectedItem) { 'Normal' { 1 } # Normal 'Minimized' { 7 } # Minimized 'Maximized' { 3 } # Maximized 'Hidden' { 7 } # Start minimized to prevent console flash before -WindowStyle Hidden takes effect default { 1 } } $shortcut.Description = "Run $(Split-Path -Path $scriptPath -Leaf) via PowerShell" $shortcut.Save() [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($wshShell) if ($chkRunAs.Checked) { $bytes = [System.IO.File]::ReadAllBytes($shortcutPath) $bytes[21] = $bytes[21] -bor 0x20 [System.IO.File]::WriteAllBytes($shortcutPath, $bytes) } $script:StatusKind = 'Success' $lblStatus.Text = "Created '$cleanName.lnk' on your Desktop." Apply-StatusStyle } catch { $script:StatusKind = 'Error' $lblStatus.Text = "Failed to create shortcut: $($_.Exception.Message)" Apply-StatusStyle } }) $btnClose.Add_Click({ $form.Close() }) [void]$form.ShowDialog() if ($null -ne $picIcon.Image) { $picIcon.Image.Dispose() } $form.Dispose() |