为什么我的脚本在Powershell ISE中可以工作,而在.ps1文件中却不能工作?

时间:2018-07-04 23:09:21

标签: powershell powershell-ise

它曾经可以工作,但现在在打开后不到一秒钟突然终止。我将执行策略设置为不受限制并重新安装了Windows,但是它仍然无法正常工作... 当使用.vbs运行Windows安全健康服务时,.ps1在任务管理器中显示1秒钟,然后消失:https://i.imgur.com/VNX7NKx.png

这是脚本(其目的是显示通知消息):

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$notifyobj = New-Object System.Windows.Forms.NotifyIcon
$notifyobj.icon = "c:/users/work/Pictures/icon.ico"
$notifyobj.BalloonTipTitle = "New Message"
$notifyobj.BalloonTipText = "C"
$notifyobj.Visible = $True
$notifyobj.ShowBalloonTip(1000)
$notifyobj.Dispose()

有关this线程的更多信息。

1 个答案:

答案 0 :(得分:0)

当然很奇怪,您应该没有任何理由必须重新安装Windows。因此,其他因素正在影响这一点。虽然很难说。

尝试使用此版本,以查看是否有任何/更多的成功。它采用了不同的方法,但是可以在我的系统上使用。

Function Show-Notification 
{            
    Param
    (
        [string]$MessageType,
        [string]$MessageText,
        [string]$MessageTitle
    )            

    #load Windows Forms and drawing assemblies            
    [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
    [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null            

    #define an icon image pulled from PowerShell.exe            
    $Icon=[system.drawing.icon]::ExtractAssociatedIcon((join-path $pshome powershell.exe))            
    $Notify = New-Object System.Windows.Forms.NotifyIcon            
    $Notify.icon = $Icon            
    $Notify.visible = $True 

    #define the tool tip icon based on the message type            
    switch ($messagetype) 
    {            
        "Error"   {$MessageIcon = [System.Windows.Forms.ToolTipIcon]::Error}            
        "Info"    {$MessageIcon = [System.Windows.Forms.ToolTipIcon]::Info}            
        "Warning" {$MessageIcon = [System.Windows.Forms.ToolTipIcon]::Warning}            
        Default   {$MessageIcon = [System.Windows.Forms.ToolTipIcon]::None}            
    }            

    #display the balloon tipe            
    $Notify.showballoontip($Notification_timeout,$MessageTitle,$MessageText,$MessageType)            
} 

Show-Notification -MessageType Info -MessageText 'some message' -MessageTitle 'New Alert'

enter image description here

enter image description here

更新

修改发布的代码以匹配我的一些项目,允许您的代码按预期在ISE控制台中工作。

[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null  
$notifyobj = New-Object System.Windows.Forms.NotifyIcon
# I don't have your icon, so, using what I know I can reach
$notifyobj.Icon = [system.drawing.icon]::ExtractAssociatedIcon((join-path $pshome powershell.exe))
$notifyobj.BalloonTipTitle = "New Message"
$notifyobj.BalloonTipText = "C"
$notifyobj.Visible = $True
$notifyobj.ShowBalloonTip(1000)
$notifyobj.Dispose()

enter image description here