当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何为 PowerShell 脚本构建 PowerShell 表单菜单

作者:精品下载站 日期:2024-12-14 20:51:50 浏览:14 分类:玩电脑

如何为 PowerShell 脚本构建 PowerShell 表单菜单


又到了周末项目时间,今天您将学习如何构建轻量级系统托盘 PowerShell 表单菜单,您可以在其中快速轻松地启动最令人垂涎的 PowerShell 脚本。您可以在下面看到最终结果。

在本文中,您将通过逐步分解该过程来学习如何构建您自己的 PowerShell 菜单 GUI。

环境和知识要求

在开始之前,请确保您满足以下最低要求:

  • Windows 7 或更高版本
  • Windows PowerShell 3 或更高版本 - 由于最近添加了对 WPF 和 WinForm 的支持,带有 PowerShell 7 预览版的最新版本 .NET Core 3.0 可能可以在 Windows 上运行,但尚未经过测试。
  • .NET Framework 4.5 或更高版本
  • 不过,熟悉 Windows 窗体 (WinForms) 也可以熟悉 WPF。

对于这个项目,好消息是您实际上不需要依赖 Visual Studio、PoshGUI 或任何其他 UI 开发工具作为该项目将依赖以下组件的主要组件:

  • NotifyIcon - 这将代表我们可定制的系统托盘图标,供用户交互。
  • ContextMenu - 用户右键单击托盘图标时的容器。
  • MenuItem - 右键单击菜单中每个选项的单独对象。

打开您最喜欢的 PowerShell 脚本编辑器,让我们开始吧!

对于此项目,您将构建三个函数:两个函数用于显示/隐藏控制台以提供更清晰的用户体验,一个函数用于向系统托盘菜单添加项目。这些功能将为以后的使用奠定基础,让您的生活变得更加轻松,您将在本文后面学到一些内容。

显示/隐藏控制台窗口

除非隐藏,否则当您启动 PowerShell 脚本时,将会出现熟悉的 PowerShell 控制台。由于您将创建的 PowerShell 表单中的菜单项将启动脚本,因此您应该确保控制台不会启动。你只是想让它执行。

执行脚本时,您可以使用一点 .NET 来切换 PowerShell 控制台窗口的显示或不显示。

首先将Window .NET 类型添加到当前会话中。为此,您将使用一些 C#,如下所示。需要加载到上下文中的两个方法是 GetConsoleWindow 和 ShowWindow。通过将这些 DLL 加载到内存中,您将公开 API 的某些部分,这允许您在 PowerShell 脚本的上下文中使用它们:

 #Load dlls into context of the current console session
 Add-Type -Name Window -Namespace Console -MemberDefinition '
    [DllImport("Kernel32.dll")]
    public static extern IntPtr GetConsoleWindow();
 
    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);

使用 GetConsoleWindow()ShowWindow() 方法使用上面加载的内容创建两个函数,如下所示。

 function Start-ShowConsole {
    $PSConsole = [Console.Window]::GetConsoleWindow()
    [Console.Window]::ShowWindow($PSConsole, 5)
 }
 
 function Start-HideConsole {
    $PSConsole = [Console.Window]::GetConsoleWindow()
    [Console.Window]::ShowWindow($PSConsole, 0)
 }

通过这两个函数,您现在已经创建了一种可以随意显示或隐藏控制台窗口的方法。

注意:如果您想查看通过菜单执行的脚本的输出,您可以使用 PowerShell 记录或其他基于文本的日志记录功能。这使您可以保持控制,而不是仅运行 PowerShell 会话并隐藏 WindowStyle 参数。

现在,通过调用 Start-HideConsole 开始构建脚本代码。当 PowerShell 表单菜单驱动脚本执行时,这将确保不会出现 PowerShell 控制台窗口。

<# 
	Initialization of functions and objects loading into memory
	Display a text-based loading bar or Write-Progress to the host
#>
 
Start-HideConsole
 
<# 
	Code to display your form/systray icon
	This will hold the console here until closed
 #>

创建菜单选项

现在是时候创建菜单选项了。确保您稍后可以轻松创建新选项,这次创建另一个名为 New-MenuItem 的函数。当您调用此函数时,它将创建一个新的 MenuItem .NET 对象,您可以稍后将其添加到菜单中。

每个菜单选项将启动另一个脚本或退出启动器。为了适应此功能,New-MenuItem 函数具有三个参数:

  • Text - 用户将点击的标签
  • MyScriptPath - 要执行的 PowerShell 脚本的路径
  • ExitOnly - 退出启动器的选项。

将以下函数片段添加到菜单脚本中。

 function New-MenuItem{
     param(
         [string]
         $Text = "Placeholder Text",
 
         $MyScriptPath,
         
         [switch]
         $ExitOnly = $false
     )

继续构建 New-MenuItem 函数,通过将其分配给变量来创建一个 MenuItem 对象。

 #Initialization
 $MenuItem = New-Object System.Windows.Forms.MenuItem

接下来,将文本标签分配给菜单项。

 # Apply desired text
 if($Text) {
 	$MenuItem.Text = $Text
 }

现在向 MenuItem 添加一个名为 MyScriptPath 的自定义属性。当在菜单中单击该项目时,将调用此路径。

 #Apply click event logic
 if($MyScriptPath -and !$ExitOnly){
 	$MenuItem | Add-Member -Name MyScriptPath -Value $MyScriptPath -MemberType NoteProperty

将单击事件添加到启动所需脚本的 MenuItem。 Start-Process 提供了一种在 try/catch 块中执行此操作的干净方法,以便您可以确保启动脚本的任何错误(例如 PowerShell 不可用或脚本在提供的路径中不存在)都落入您的 catch 块中。

   $MenuItem.Add_Click({
        try{
            $MyScriptPath = $This.MyScriptPath #Used to find proper path during click event
            
            if(Test-Path $MyScriptPath){
                Start-Process -FilePath "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ArgumentList "-NoProfile -NoLogo -ExecutionPolicy Bypass -File `"$MyScriptPath`"" -ErrorAction Stop
            } else {
                throw "Could not find at path: $MyScriptPath"
            }
        } catch {
          $Text = $This.Text
          [System.Windows.Forms.MessageBox]::Show("Failed to launch $Text`n`n$_") > $null
        }
  })

添加剩余的逻辑以为启动器提供退出条件,然后返回新创建的 MenuItem 以在运行时分配给另一个变量。

    #Provide a way to exit the launcher
    if($ExitOnly -and !$MyScriptPath){
        $MenuItem.Add_Click({
            $Form.Close()
    
            #Handle any hung processes
            Stop-Process $PID
        })
    }
 
 	 #Return our new MenuItem
    $MenuItem
 }

您现在应该已经创建了 New-MenuItem 函数!最终的函数应该是这样的:

 function New-MenuItem{
     param(
         [string]
         $Text = "Placeholder Text",
 
         $MyScriptPath,
         
         [switch]
         $ExitOnly = $false
     )
 
     #Initialization
     $MenuItem = New-Object System.Windows.Forms.MenuItem
 
     #Apply desired text
     if($Text){
         $MenuItem.Text = $Text
     }
 
     #Apply click event logic
     if($MyScriptPath -and !$ExitOnly){
         $MenuItem | Add-Member -Name MyScriptPath -Value $MyScriptPath -MemberType NoteProperty
     }
 
     $MenuItem.Add_Click({
             try{
                 $MyScriptPath = $This.MyScriptPath #Used to find proper path during click event
             
                 if(Test-Path $MyScriptPath){
                     Start-Process -FilePath "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ArgumentList "-NoProfile -NoLogo -ExecutionPolicy Bypass -File `"$MyScriptPath`"" -ErrorAction Stop
                 } else {
                     throw "Could not find at path: $MyScriptPath"
                 }
             } catch {
                 $Text = $This.Text
                 [System.Windows.Forms.MessageBox]::Show("Failed to launch $Text`n`n$_") > $null
             }
         })
 
     #Provide a way to exit the launcher
     if($ExitOnly -and !$MyScriptPath){
         $MenuItem.Add_Click({
                 $Form.Close()
    
                 #Handle any hung processes
                 Stop-Process $PID
             })
     }
 
     #Return our new MenuItem
     $MenuItem
 }

通过将上述代码复制并粘贴到 PowerShell 控制台并运行提供一些假参数值的函数来测试 New-MenuItem 函数。您将看到返回了一个 .NET MenuItem 对象。

 PS51> (New-MenuItem -Text "Test" -MyScriptPath "C:\test.ps1").GetType()
 
 IsPublic IsSerial Name                                     BaseType
 -------- -------- ----                                     --------
 True     False    MenuItem                                 System.Windows.Forms.Menu

创建启动器表单

想要更多这样的提示吗?查看我的个人 PowerShell 博客:https://nkasco.com/FriendsOfATA

现在您可以轻松创建新的菜单项,是时候创建一个将显示菜单的系统托盘启动器了。

创建一个基本表单对象以添加组件。这不需要什么花哨的东西,因为它将对最终用户隐藏,并且也会使控制台在后台运行。

 #Create Form to serve as a container for our components
 $Form = New-Object System.Windows.Forms.Form
 
 #Configure our form to be hidden
 $Form.BackColor = "Magenta" #Match this color to the TransparencyKey property for transparency to your form
 $Form.TransparencyKey = "Magenta"
 $Form.ShowInTaskbar = $false
 $Form.FormBorderStyle = "None"

接下来,创建将显示在系统托盘中的图标。下面我选择使用 PowerShell 图标。在运行时,以下代码创建一个实际的系统托盘图标。通过将 SystrayIcon 变量设置为您想要的图标,可以根据您的喜好自定义此图标。

查看 System.Drawing.Icon 类的文档,了解可将图标加载到内存中的其他方法。

 #Initialize/configure necessary components
 $SystrayLauncher = New-Object System.Windows.Forms.NotifyIcon
 $SystrayIcon = [System.Drawing.Icon]::ExtractAssociatedIcon("C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe")
 $SystrayLauncher.Icon = $SystrayIcon
 $SystrayLauncher.Text = "PowerShell Launcher"
 $SystrayLauncher.Visible = $true

运行脚本后,您应该会看到系统托盘中出现一个 PowerShell 图标,如下所示。

现在,使用新的 ContextMenu 对象为菜单项创建一个容器,并创建所有菜单项。对于此示例,菜单将有两个要运行的脚本和一个退出选项。

 $ContextMenu = New-Object System.Windows.Forms.ContextMenu
 
 $LoggedOnUser = New-MenuItem -Text "Get Logged On User" -MyScriptPath "C:\scripts\GetLoggedOn.ps1"
 $RestartRemoteComputer = New-MenuItem -Text "Restart Remote PC" -MyScriptPath "C:\scripts\restartpc.ps1"
 $ExitLauncher = New-MenuItem -Text "Exit" -ExitOnly

接下来,将刚刚创建的所有菜单项添加到上下文菜单中。这将确保每个菜单选项显示在表单上下文菜单中。

 #Add menu items to context menu
 $ContextMenu.MenuItems.AddRange($LoggedOnUser)
 $ContextMenu.MenuItems.AddRange($RestartRemoteComputer)
 $ContextMenu.MenuItems.AddRange($ExitLauncher)
 
 #Add components to our form
 $SystrayLauncher.ContextMenu = $ContextMenu

显示启动器表单

现在表单已完成,最后要做的就是显示它,同时确保 PowerShell 控制台窗口不会出现。为此,请使用 Start-HideConsole ,显示启动器表单,然后使用 Start-ShowConsole 再次显示控制台,以防止挂起 powershell.exe 过程。

#Launch
Start-HideConsole
$Form.ShowDialog() > $null
Start-ShowConsole

想要更多这样的提示吗?查看我的个人 PowerShell 博客:https://nkasco.com/FriendsOfATA

完整的代码可以在这里找到:https://github.com/nkasco/PSSystrayLauncher

您的收获

恭喜,您已经完成了这个项目!在本文中您了解到:

  1. 如何公开 Windows API 的组件。
  2. 如何通过 WinForms 使用上下文菜单并添加后续菜单项。
  3. 如何在 PowerShell 中创建系统托盘图标。

这个项目应该给你足够的理解和经验来为你的PowerShell脚本创建你自己的系统托盘菜单!

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯