powershell - 从任务计划程序运行的 PowerShell 脚本中的 Msgbox 不起作用
问题描述
我有一个 PowerShell 脚本,它创建一个计划任务来启动脚本。这个想法是脚本中有一些需要重新启动的任务。在 PowerShell 结束时,一个消息框应提示用户让用户知道所有任务都已完成。我究竟做错了什么?
Add-Type -AssemblyName PresentationFramework
TaskName = "Run Agents Install Script"
$TaskDescription = "Run Agents Install Script at logon"
$Action = New-ScheduledTaskAction -Execute 'Powershell.exe' `
-Argument "-executionpolicy remotesigned -File $PSScriptRoot\AgentInstall.ps1"
$Trigger = New-ScheduledTaskTrigger -AtLogOn
Register-ScheduledTask -Action $Action -Trigger $Trigger -TaskName $TaskName -Description $TaskDescription -User "System"
$MsgBoxInput = [System.Windows.MessageBox]::Show('Installation completed successfully.','Agent Install','OK')
Switch ($MsgBoxInput) {
'OK'
{
$MsgBoxInput = [System.Windows.MessageBox]::Show('WARNING! Please install Imprivata agent manually if applicable.','Agent Install','OK')
}
}
解决方案
一种选择是使用终端服务 API 向控制台发送消息。不幸的是,它是本机 API,因此您需要使用 .NET 互操作来调用它,但在这种情况下它并不太棘手:
$typeDefinition = @"
using System;
using System.Runtime.InteropServices;
public class WTSMessage {
[DllImport("wtsapi32.dll", SetLastError = true)]
public static extern bool WTSSendMessage(
IntPtr hServer,
[MarshalAs(UnmanagedType.I4)] int SessionId,
String pTitle,
[MarshalAs(UnmanagedType.U4)] int TitleLength,
String pMessage,
[MarshalAs(UnmanagedType.U4)] int MessageLength,
[MarshalAs(UnmanagedType.U4)] int Style,
[MarshalAs(UnmanagedType.U4)] int Timeout,
[MarshalAs(UnmanagedType.U4)] out int pResponse,
bool bWait
);
static int response = 0;
public static int SendMessage(int SessionID, String Title, String Message, int Timeout, int MessageBoxType) {
WTSSendMessage(IntPtr.Zero, SessionID, Title, Title.Length, Message, Message.Length, MessageBoxType, Timeout, out response, true);
return response;
}
}
"@
Add-Type -TypeDefinition $typeDefinition
[WTSMessage]::SendMessage(1, "Message Title", "Message body", 30, 36)
这本质上是对WTSSendMessage函数的精简包装。
您将需要SessionID
通过一些工具(例如query
. 该脚本可能对此有所帮助:Get-UserSession。
这里的TimeOut
值是 30,这意味着弹出窗口将等待 30 秒,然后返回值“32000”。设置为“0”以永久等待。
这MessageBoxType
是uType
此处的值的组合:MessageBox Function。因此示例中的“36”是“MB_YESNO”和“MB_ICONQUESTION”值的组合,因此将显示带有问号图标和“是”/“否”按钮的消息。请注意,文档以十六进制形式提供了值,因此您需要对其进行转换。
我将此作为以管理员身份运行的计划任务进行了测试,它能够在不同登录用户的桌面上显示一条消息。希望能帮助到你。
推荐阅读
- agda - 如何从明确的尺寸减小证明转变为停止减少算法?
- python - 处理熊猫数据框中的inf?
- scikit-learn - 如何使用 LGBM 特征重要性和 Tfidf 矢量化器获取重要词?
- c# - 如何获取动态类型的属性
- snowflake-cloud-data-platform - 根据 oracle 输入数据对雪花表执行 SCD2
- vba - 如何修复 AllowEdits 按钮上的“找不到方法或数据成员”
- regex - 通过shell终端仅使用正则表达式仅提取(从文本中)非重复单词
- c# - 我的数组类错误 CS0120 C# 的问题
- postgresql - 用条件计算 PostgreSQL
- ansible - ansible 变量参考:ssh 和命令后无法从寄存器变量中读取 stdout_lines