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://jdhitsolutions.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

相关内容