我有一个PowerShell脚本,该脚本具有在有人输入计算机名称时提取LAPS信息的功能。我想在60秒后清除输出,以免有人意外在屏幕上留下密码。
似乎无论该函数在何处睡眠(或什至之后),脚本都会暂停60秒,然后显示信息,并且永远不会清除。
脚本中等待并清除的部分:
Start-Sleep -s 60
$WPFOutputbox.Clear()
(在下面查找我的#TRIED HERE
条评论)
function GETLAPS {
Param ($computername = $WPFComputer.Text)
try {
$LAPSComputer = Get-AdmPwdPassword -ComputerName $computername |
Select-Object -ExpandProperty computername
$LAPSDistinguished = Get-AdmPwdPassword -ComputerName $computername |
Select-Object -ExpandProperty distinguishedname
$LAPSPassword = Get-AdmPwdPassword -ComputerName $computername |
Select-Object -ExpandProperty Password
$LAPSExpire = Get-AdmPwdPassword -ComputerName $computername |
Select-Object -ExpandProperty Expirationtimestamp
} catch {
$ErrorMessage = $_.Exception.Message
}
if ($ErrorMessage -eq $null) {
$WPFOutputBox.Foreground = "Blue"
$WPFOutputBox.Text = "Local Admin Information for: $LAPSComputer
Current: $LAPSPassword
Exipiration: $LAPSExpire
SCREEN WILL CLEAR AFTER 60 SECONDS"
#TRIED HERE
} else {
$WPFOutputBox.Foreground = "Red"
$WPFOutputBox.Text = $ErrorMessage
}
#TRIED HERE
}
相反,脚本将等待60秒才能显示信息,并且永远不会清除屏幕。
答案 0 :(得分:1)
除非您创建单独的线程,否则我强烈建议不要在Start-Sleep
cmdlet或Windows Forms中使用Windows Presentation Foundation,因为它显然会使用户界面停滞。
相反,我建议使用(Windows.Forms.Timer
)事件。
为此,我编写了一个小函数来延迟命令:
Function Delay-Command([ScriptBlock]$Command, [Int]$Interval = 100, [String]$Id = "$Command") {
If ($Timers -isnot "HashTable") {$Global:Timers = @{}}
$Timer = $Timers[$Id]
If (!$Timer) {
$Timer = New-Object Windows.Forms.Timer
$Timer.Add_Tick({$This.Stop()})
$Timer.Add_Tick($Command)
$Global:Timers[$Id] = $Timer
}
$Timer.Stop()
$Timer.Interval = $Interval
If ($Interval -gt 0) {$Timer.Start()}
}; Set-Alias Delay Delay-Command
Delay {$WpFOutputBox.Text = ''} 60000
-Command
该命令将被延迟。
-Interval
执行command
之前需要等待的时间。
如果-Interval
设置为0
以下,则command
(以及相关的Id
)将被重置。
默认值为100
(经过短时间才能使其他事件开始)。
-Id
延迟命令的Id
。可以同时执行不同Id
的多个命令。如果相同的Id
用于尚未执行的命令,则间隔计时器将重置(或设置为0
时取消)。
命令字符串中的默认Id
。
答案 1 :(得分:-1)
调用该函数,睡眠60秒钟,然后将其清除。不要将睡眠放在函数内部,而应将其放在调用函数的位置。像这样:
$WPFGetLAPSButton.add_click({
GETLAPS
# If no error, wait 60 seconds and clear the text box
If($WPFOutputBox.Foreground -eq "Blue"){
Start-Sleep 60
$WPFOutputBox.Text = ''
}
})
可以肯定会满足您的需求。