首页 > 解决方案 > 如果函数成功运行,PowerShell 将显示消息

问题描述

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

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

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

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

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

谢谢

标签: powershell

解决方案


Restart-Explorer你可以在一个函数中做这两件事。

除非给出开关,否则Stop-Process不会返回任何内容。PassThru将其与 结合使用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

希望有帮助


推荐阅读