Msgbox in PowerShell script run from task scheduler not working

£可爱£侵袭症+ 提交于 2019-11-29 17:24:34

One option is to use the Terminal Services API to send a message to the console. Unfortunately, it is native API, so you need to use .NET interop to call it, but in this case it isn't too tricky:

$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)

This is essentially a thin wrapper to the WTSSendMessage function.

You will need to get the SessionID via some tool like query. This script might help with that: Get-UserSession.

The TimeOut value here is 30, which means the pop-up will wait 30 seconds before returning with a value of '32000'. Set to '0' to wait forever.

The MessageBoxType is a combination of the values for uType here: MessageBox Function. So the '36' in the example is a combination of the values for 'MB_YESNO' and 'MB_ICONQUESTION', so will show a message with a question mark icon and 'yes'/'no' buttons. Note that the documentation gives the values in hexadecimal, so you'll need to convert them.

I tested this as a scheduled task running as an admin and it was able to show a message on the desktop of a different logged on user. hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!