Powershell - 如何顯示訊息並將使用者輸入儲存到日誌文件

Powershell - 如何顯示訊息並將使用者輸入儲存到日誌文件

我花了一整天的時間研究實現這一目標的最佳和最簡單的方法,但似乎沒有一個。我已經找到了一些零碎的東西,但我還沒能成功地讓它們發揮作用。我只是想透過執行 Powershell 腳本向用戶顯示彈出訊息。我想讓腳本執行以下操作:

1. The popup would give an action for input by the user, 
2. The message will tell them their computer will be restarted to complete a Windows 1809 upgrade, 
3. The user will click ok and the input, along with the username and machine name will be sent to a log file. 
4. The script would have a timer on it that will restart the computer within 30 minutes whether the input is given or not. 

下面的程式碼做了我想要的事情,減去了計時器,但沒有給用戶帶來彈出訊息。它只是在 Powershell 控制台中給出訊息。我怎麼能讓它做同樣的事情,但在彈出訊息中呢?

$HostName = $env:COMPUTERNAME
$PatchLocation = "c:\Temp\"
$LogFile = "responses.log"
$LogPath = $PatchLocation + $LogFile
$date = Get-Date

$response = Invoke-Command -ComputerName $HostName -ScriptBlock{ Read-Host "Your computer will be restarted in 30 minutes. Please save your work. Type 'Agree' If you have saved your work"}

"Response for $HostName is $response - $date"|Out-File -FilePath $LogPath -Append

答案1

看一眼https://jdhisolutions.com/blog/powershell/2976/powershell-popup/

在最近的 PowerShell 高峰會上,我舉辦了一場關於在不需要 WinForms 或 WPF 的情況下為腳本添加圖形元素的會議。我演示的項目之一是圖形彈出窗口,它可以要求用戶單擊按鈕或在設定的時間段後自動關閉。如果這聽起來很熟悉,是的,它就是我們的老朋友 VBScript 和 Wscript.Shell 物件的 Popup 方法。既然 PowerShell 可以建立和使用 COM 對象,為什麼不利用這一點呢?

$wshell = New-Object -ComObject Wscript.Shell -ErrorAction Stop
$wshell.Popup("Are you looking at me?",0,"Hey!",48+4)

答案2

感謝 Hans Hubert Vogts,提供了彈出訊息的代碼。它提供了彈出窗口,但是,我需要腳本來輸出到日誌檔案。我修改了程式碼來做到這一點。它在下面。

#https://jdhitsolutions.com/blog/powershell/2976/powershell-popup/
#For reference

$HostName = $env:COMPUTERNAME
$PatchLocation = "c:\Temp\"
$LogFile = "responses.log"
$LogPath = $PatchLocation + $LogFile
$date = Get-Date

$wshell = New-Object -ComObject Wscript.Shell -ErrorAction Stop 
$result = $wshell.Popup("Your Computer will be Restarted in 30 Minutes",30,"Hey!",48+4)

"Response for $HostName is $result - $date"|Out-File -FilePath $LogPath -Append

相關內容