【问题标题】:How to run a powershell script in the background and receive a toast notification?如何在后台运行 powershell 脚本并接收 toast 通知?
【发布时间】:2020-02-26 15:04:20
【问题描述】:

this question 的答案解决了我的问题的第一部分。

不幸的是,当我安排一个隐藏 powershell 窗口的作业时,我的脚本发送的任何 toast 通知都不会显示。 该脚本使用此脚本 (source) 显示 toast 通知:

Add-Type -AssemblyName System.Windows.Forms 
$global:balloon = New-Object System.Windows.Forms.NotifyIcon
$path = (Get-Process -id $pid).Path
$balloon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path) 
$balloon.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Warning 
$balloon.BalloonTipText = 'What do you think of this balloon tip?'
$balloon.BalloonTipTitle = "Attention $Env:USERNAME" 
$balloon.Visible = $true 
$balloon.ShowBalloonTip(5000)

当我以不隐藏的方式安排 powershell 脚本时,会显示通知,但每次触发脚本时,我都会短暂地看到一个 powershell 窗口。

如何安排隐藏 powershell 窗口但显示 toast 通知的任务或作业?

【问题讨论】:

标签: powershell push-notification scheduled-tasks job-scheduling


【解决方案1】:

Powershell.exe 是一个控制台应用程序。进程启动时,操作系统会自动创建控制台窗口。因此,处理 -WindowStyle Hidden 的 powershell.exe 代码在控制台窗口打开后执行,因此会闪烁。我喜欢用VB脚本启动PowerShell来保证完全隐藏的体验

输入,比如ps-run_hidden.vbs put

Set objShell = CreateObject("Wscript.Shell")
Set args = Wscript.Arguments
For Each arg In args
    objShell.Run("powershell -windowstyle hidden -executionpolicy bypass -noninteractive ""&"" ""'" & arg & "'"""),0
Next

然后用它来运行你想要的命令,例如像这样来自 Windows 的计划任务

wscript "C:\Path\To\ps-run_hidden.vbs" "C:\Other\Path\To\your-script.ps1"

您现在可以运行任务而不会看到任何闪烁的窗口。

【讨论】:

  • 我选择了这个解决方案,因为它可以让我继续使用熟悉的任务调度程序。
【解决方案2】:

您可以在后台将其作为作业运行,这样不会弹出窗口并显示您的消息,

注意:在 Start-Job 之外声明的任何变量都需要像 $using:variable 一样使用。如果 $pid 在 Start-Job 之外声明,您将使用 $using:pid。

Start-Job -ScriptBlock { 
    Add-Type -AssemblyName System.Windows.Forms 
    $global:balloon = New-Object System.Windows.Forms.NotifyIcon
    $path = (Get-Process -id $using:pid).Path
    $balloon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path) 
    $balloon.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Warning 
    $balloon.BalloonTipText = 'What do you think of this balloon tip?'
    $balloon.BalloonTipTitle = "Attention $Env:USERNAME" 
    $balloon.Visible = $true 
    $balloon.ShowBalloonTip(5000)
} | Wait-Job | Remove-Job

在 ps1 文件中包含上述代码后,只需调用以下行。它不会显示powershell窗口并为您提供通知窗口。

powershell -File myScript.ps1 -WindowStyle Hidden

【讨论】:

  • 这并没有隐藏 powershell 进程的启动阶段。它会在读取 WindowStyle 属性之前弹出几毫秒。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多