每 3 秒清除 memory/Buffer 的 powershell 运行 无限循环

clear memory/Buffer of powershell running endless loop every 3 seconds

我创建了一个 powershell 脚本,它只是解析日志文件,如果最后一行包含关键字 "error",它会发送一封电子邮件并运行一个微型鼠标宏 - 循环每 3 秒重复一次 - 无限循环

if ($lastSent -ne $currentLine -and $currentLine -match "Error") {
            if ($currentLine -match "Error23") {
                [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(225, 305)
                sleep -Seconds 01
                $SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
                $SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
                sleep -Seconds 01
                [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(60, 305)
                sleep -Seconds 01
                $SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
                $SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
                sleep -Seconds 01

}

我过去测试过,离开 运行 应用程序好几天了,现在它 运行 应用程序和这个 powershell 脚本。

然而,在 12 小时到 18 小时之后,有时甚至一天左右,计算机会死机,我无法进行 RDP 或 ping 或任何操作,完全死机 - 所以这是 powershell 脚本导致的。

有人可以告诉我任何 powershell 命令或我可以将其添加到清除内存或缓冲区的循环中的东西吗

谢谢

如果您未对脚本进行任何更改并且它在过去运行良好,那么恕我直言,该脚本将不是我的第一个故障排除目标。

您的系统上的某些环境发生了变化。表示该应用程序或主机本身。

你可以强制垃圾回收,这是一种方式……

### Clear resource environment

Function Clear-ResourceEnvironment
{
    # Clear any PowerShell sessions created
    Get-PSSession | Remove-PSSession

    # Release an COM object created
    $null = [System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$Shell)

    # Perform garbage collection on session resources 
    [System.GC]::Collect()         
    [GC]::Collect()
    [GC]::WaitForPendingFinalizers()

    # Remove any custom varialbes created
    Get-Variable -Name MyShell -ErrorAction SilentlyContinue | Remove-Variable
}

就个人而言,我真的无法想象你为什么选择这种方法,而不是让这个永久的 WMI 观察器,或者说这样做......

实时监控日志...

# Take action as soon as the incoming line equals error
Get-Content -Path .\SomeLogFileName -Wait -Tail 0 | 
Where-Object {$_ -match 'error'}

你为什么多次调用这个?

[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(60, 305)
sleep -Seconds 01
$SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
$SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);

称之为...

[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(60, 305)

...在脚本的顶部。

制作这个...

sleep -Seconds 01
$SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
$SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
sleep -Seconds 01

...一个函数并调用该函数 vs 复制代码,所以,类似。

Function Send-MouseClick
{
    sleep -Seconds 01
    $SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
    $SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
    sleep -Seconds 01    
}

if ($lastSent -ne $currentLine -and $currentLine -match "Error") 
{
    if ($currentLine -match "Error23") {
    Send-MouseClick
}

只是我的一些想法,但显然没有经过测试。