【问题标题】:PowerShell to display message if function ran successfully如果函数成功运行,PowerShell 将显示消息
【发布时间】:2020-04-10 03:36:58
【问题描述】:

我有一个简单的 ps 脚本来重新启动 Windows 资源管理器的进程。我有这个功能:

Function Restart-Explorer()
{
    Stop-Process -ProcessName explorer
}

Function ranFunction
{
    if (Restart-Explorer) {
        "Success"
    }
    else {
        "failed"
    }
}

我只是不知道函数是否成功运行时如何显示弹出消息。

有人能指出我正确的方向吗?我可以学习的资源将非常有帮助。

谢谢

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您可以在一个 Restart-Explorer 函数中完成这两件事。

    除非给出PassThru 开关,否则Stop-Process 不会返回任何内容。将其与ErrorAction SilentlyContinue 结合使用,您可以事后检查对象是否返回(成功)或不返回(失败)。

    类似这样的:

    function Restart-Explorer {
        $proc = Stop-Process -Name explorer -PassThru -ErrorAction SilentlyContinue
        if ($proc) { 
            $msg = "Success"
            $icon = "Information"
        } 
        else { 
            $msg = "Failed"
            $icon = "Critical"
        }
        Add-Type -AssemblyName Microsoft.VisualBasic
        [Microsoft.VisualBasic.Interaction]::MsgBox($msg, "OKOnly,SystemModal,$Icon", "Restart Explorer")
    }
    
    Restart-Explorer
    

    我在这里使用[Microsoft.VisualBasic.Interaction]::MsgBox() 方法,因为它可以通过添加SystemModal 来确保对话框位于最顶层

    希望有帮助

    【讨论】:

    • 感谢您的回复!这工作得很好。干杯
    • 谢谢,我刚刚注意到我有notepad,而不是explorer。那是在我的机器上进行的测试。现已修复
    【解决方案2】:

    如果您想要的只是用户需要通过消息确认的弹出窗口,您可以将以下内容添加到您的代码中。

    [System.Windows.MessageBox]::Show( 'Message here','Window Title','OK','Window Type[Information,Error,Warning]')
    

    因此,这将是我的建议:

    Function Restart-Explorer()
    {
        Stop-Process -ProcessName explorer
    }
    
    Function ranFunction
    {
        if (Restart-Explorer) {
            [System.Windows.MessageBox]::Show( 'Message Here','Some Title','OK','Information')
        }
        else {
            [System.Windows.MessageBox]::Show( 'Message Here','Some Title','OK','Error')
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-07
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      相关资源
      最近更新 更多