簡體   English   中英

從任務計划程序運行的PowerShell腳本中的Msgbox無法正常工作

[英]Msgbox in PowerShell script run from task scheduler not working

我有一個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 interop來調用它,但是在這種情況下,它並不是很棘手:

$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函數的精簡包裝。

您將需要通過諸如query工具獲取SessionID 該腳本可能會幫助您: Get-UserSession

這里的TimeOut值為30,這意味着彈出窗口將等待30秒,然后返回值32000。 設置為“ 0”將永遠等待。

MessageBoxType是此處uType的值的組合: MessageBox Function 因此,示例中的“ 36”是“ MB_YESNO”和“ MB_ICONQUESTION”的值的組合,因此將顯示帶有問號圖標和“是” /“否”按鈕的消息。 請注意,文檔以十六進制形式提供值,因此您需要對其進行轉換。

我將其作為管理員運行的計划任務進行了測試,它能夠在其他登錄用戶的桌面上顯示一條消息。 希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM