Skip to content

Instantly share code, notes, and snippets.

@benevides
Forked from AveYo/.FreeStandbyMemory.bat
Created September 30, 2021 13:34
Show Gist options
  • Select an option

  • Save benevides/d48898800c71113b75e0947cee2196b7 to your computer and use it in GitHub Desktop.

Select an option

Save benevides/d48898800c71113b75e0947cee2196b7 to your computer and use it in GitHub Desktop.

Revisions

  1. @AveYo AveYo revised this gist Jun 1, 2019. 1 changed file with 9 additions and 9 deletions.
    18 changes: 9 additions & 9 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -12,14 +12,14 @@ reg query "HKEY_USERS\S-1-5-20\Environment" /v TEMP >nul 2>nul || (
    )

    :: add_remove whenever script is run again
    ::schtasks /query /tn FreeStandbyMemory >nul 2>nul && (
    :: echo.
    :: schtasks /Delete /TN "FreeStandbyMemory" /f 2>nul
    :: reg delete HKLM\Software\AveYo /v FreeStandbyMemory /f 2>nul
    :: del /f /q "%Windir%\FreeStandbyMemory.exe" 2>nul
    :: color 0b &echo. &echo REMOVED! Run script again to recompile and add schedule!
    :: timeout /t -1 &color 0f &title %COMSPEC% &exit/b
    ::)
    schtasks /query /tn FreeStandbyMemory >nul 2>nul && (
    echo.
    schtasks /Delete /TN "FreeStandbyMemory" /f 2>nul
    reg delete HKLM\Software\AveYo /v FreeStandbyMemory /f 2>nul
    del /f /q "%Windir%\FreeStandbyMemory.exe" 2>nul
    color 0b &echo. &echo REMOVED! Run script again to recompile and add schedule!
    timeout /t -1 &color 0f &title %COMSPEC% &exit/b
    )

    :: compile c# snippet
    pushd %~dp0
    @@ -129,7 +129,7 @@ namespace FreeStandbyMemory
    RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE, true, false, out retv);
    NtSetSystemInformation(SystemMemoryListInformation, out MemoryPurgeStandbyList, Marshal.SizeOf(MemoryPurgeStandbyList));
    if (systemcachews) {
    SetSystemFileCacheSize(IntPtr.Subtract(IntPtr.Zero, 1), IntPtr.Subtract(IntPtr.Zero, 1), 0);
    SetSystemFileCacheSize(new IntPtr(-1), new IntPtr(-1), 0);
    Process[] processlist = Process.GetProcesses(); // Also free system processes working sets:
    foreach(Process p in processlist) if (p.SessionId == 0) try { EmptyWorkingSet(p.Handle); } catch (Exception) {}
    }
  2. @AveYo AveYo revised this gist Jun 1, 2019. 1 changed file with 41 additions and 41 deletions.
    82 changes: 41 additions & 41 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -12,14 +12,14 @@ reg query "HKEY_USERS\S-1-5-20\Environment" /v TEMP >nul 2>nul || (
    )

    :: add_remove whenever script is run again
    schtasks /query /tn FreeStandbyMemory >nul 2>nul && (
    echo.
    schtasks /Delete /TN "FreeStandbyMemory" /f 2>nul
    reg delete HKLM\Software\AveYo /v FreeStandbyMemory /f 2>nul
    del /f /q "%Windir%\FreeStandbyMemory.exe" 2>nul
    color 0b &echo. &echo REMOVED! Run script again to recompile and add schedule!
    timeout /t -1 &color 0f &title %COMSPEC% &exit/b
    )
    ::schtasks /query /tn FreeStandbyMemory >nul 2>nul && (
    :: echo.
    :: schtasks /Delete /TN "FreeStandbyMemory" /f 2>nul
    :: reg delete HKLM\Software\AveYo /v FreeStandbyMemory /f 2>nul
    :: del /f /q "%Windir%\FreeStandbyMemory.exe" 2>nul
    :: color 0b &echo. &echo REMOVED! Run script again to recompile and add schedule!
    :: timeout /t -1 &color 0f &title %COMSPEC% &exit/b
    ::)

    :: compile c# snippet
    pushd %~dp0
    @@ -69,28 +69,28 @@ namespace FreeStandbyMemory
    static int MemoryPurgeStandbyList = 0x0004;
    const int SystemFileCacheInformation = 0x0015;
    const int SystemMemoryListInformation = 0x0050;
    const uint SE_INCREASE_QUOTA_PRIVILEGE = 0x00000005;
    const uint SE_PROF_SINGLE_PROCESS_PRIVILEGE = 0x0000000d;
    const int SE_INCREASE_QUOTA_PRIVILEGE = 0x00000005;
    const int SE_PROF_SINGLE_PROCESS_PRIVILEGE = 0x0000000d;
    [StructLayout(LayoutKind.Sequential)]
    private class PERFINFO
    {
    public uint cb;
    public UIntPtr CommitTotal;
    public UIntPtr CommitLimit;
    public UIntPtr CommitPeak;
    public UIntPtr PhysicalTotal;
    public UIntPtr PhysicalAvailable;
    public UIntPtr SystemCache;
    public UIntPtr KernelTotal;
    public UIntPtr KernelPaged;
    public UIntPtr KernelNonpaged;
    public UIntPtr PageSize;
    public uint HandleCount;
    public uint ProcessCount;
    public uint ThreadCount;
    public int cb;
    public IntPtr CommitTotal;
    public IntPtr CommitLimit;
    public IntPtr CommitPeak;
    public IntPtr PhysicalTotal;
    public IntPtr PhysicalAvailable;
    public IntPtr SystemCache;
    public IntPtr KernelTotal;
    public IntPtr KernelPaged;
    public IntPtr KernelNonpaged;
    public IntPtr PageSize;
    public int HandleCount;
    public int ProcessCount;
    public int ThreadCount;
    public PERFINFO()
    {
    this.cb = (uint)Marshal.SizeOf(typeof(PERFINFO));
    this.cb = (int)Marshal.SizeOf(typeof(PERFINFO));
    }
    }
    [return: MarshalAs(UnmanagedType.Bool)]
    @@ -101,33 +101,33 @@ namespace FreeStandbyMemory
    [DllImport("kernel32.dll")]
    static extern bool SetSystemFileCacheSize(IntPtr MinimumFileCacheSize, IntPtr MaximumFileCacheSize, int Flags);
    [DllImport("ntdll.dll")]
    static extern uint RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool RetValue);
    static extern IntPtr RtlAdjustPrivilege(int Privilege, bool Enable, bool CurrentThread, out bool RetValue);
    [DllImport("ntdll.dll")]
    static extern uint NtSetSystemInformation(int InfoClass, ref int Info, int Length);
    static extern IntPtr NtSetSystemInformation(int InfoClass, out int Info, int Length);

    static void Main(string[] args)
    {
    ulong target = (args.Length == 0) ? UInt64.MaxValue : Convert.ToUInt64(args[0]);
    int target = (args.Length == 0) ? Int32.MaxValue : Convert.ToInt32(args[0]);
    bool systemcachews = (args.Length == 0 || args.Length >= 2 && args[1] == "1");
    ulong free = 0;
    Int64 free = 0;
    PERFINFO pi = new PERFINFO();
    if (GetPerformanceInfo(pi))
    {
    ulong avail = (ulong)pi.PhysicalAvailable;
    ulong cache = (ulong)pi.SystemCache;
    ulong page = (ulong)pi.PageSize;
    free = (page * ( (avail > cache) ? avail - cache : cache - avail) ) >> 20;
    Int64 avail = pi.PhysicalAvailable.ToInt64();
    Int64 cache = pi.SystemCache.ToInt64();
    Int64 page = pi.PageSize.ToInt64();
    free = ( (avail > cache) ? avail - cache : cache - avail ) * page >> 20;
    /* To debug, change csc /target:winexe to /target:exe and uncomment the Console.WriteLine's */
    //Console.WriteLine("Total: {0,5}MB", (page*(ulong)pi.PhysicalTotal >> 20));
    //Console.WriteLine("Avail: {0,5}MB", (page*(ulong)pi.PhysicalAvailable >> 20));
    //Console.WriteLine("Cache: {0,5}MB", (page*(ulong)pi.SystemCache >> 20));
    //Console.WriteLine("Free: {0,5}MB", free);
    ////Console.WriteLine("Total: {0,5}MB", pi.PhysicalTotal.ToInt64() * page >> 20);
    ////Console.WriteLine("Avail: {0,5}MB", pi.PhysicalAvailable.ToInt64() * page >> 20);
    ////Console.WriteLine("Cache: {0,5}MB", pi.SystemCache.ToInt64() * page >> 20);
    ////Console.WriteLine("Free: {0,5}MB", free);
    }
    if (free > target) return;
    //Console.WriteLine("Target:{0,5}MB - CLEARING!", target);
    RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE, true, false, ref retv);
    RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE, true, false, ref retv);
    NtSetSystemInformation(SystemMemoryListInformation, ref MemoryPurgeStandbyList, Marshal.SizeOf(MemoryPurgeStandbyList));
    ////Console.WriteLine("Target:{0,5}MB - CLEARING!", target);
    RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE, true, false, out retv);
    RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE, true, false, out retv);
    NtSetSystemInformation(SystemMemoryListInformation, out MemoryPurgeStandbyList, Marshal.SizeOf(MemoryPurgeStandbyList));
    if (systemcachews) {
    SetSystemFileCacheSize(IntPtr.Subtract(IntPtr.Zero, 1), IntPtr.Subtract(IntPtr.Zero, 1), 0);
    Process[] processlist = Process.GetProcesses(); // Also free system processes working sets:
  3. @AveYo AveYo revised this gist Jun 1, 2019. 1 changed file with 12 additions and 5 deletions.
    17 changes: 12 additions & 5 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -24,7 +24,7 @@ schtasks /query /tn FreeStandbyMemory >nul 2>nul && (
    :: compile c# snippet
    pushd %~dp0
    del /f /q FreeStandbyMemory.exe >nul 2>nul
    for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%Windir%\Microsoft.NET\Framework\*csc.exe"') do set "csc="%%v""
    for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%Windir%\Microsoft.NET\*csc.exe"') do set "csc="%%v""
    %csc% /out:FreeStandbyMemory.exe /target:winexe /platform:anycpu /optimize /nologo "%~f0"
    if not exist FreeStandbyMemory.exe echo ERROR! Failed compiling c# snippet & timeout /t -1 & exit /b
    echo|set/p=FreeStandbyMemory.exe &copy /y FreeStandbyMemory.exe "%Windir%\FreeStandbyMemory.exe" &set "OUTDIR=%Windir%"
    @@ -109,15 +109,22 @@ namespace FreeStandbyMemory
    {
    ulong target = (args.Length == 0) ? UInt64.MaxValue : Convert.ToUInt64(args[0]);
    bool systemcachews = (args.Length == 0 || args.Length >= 2 && args[1] == "1");
    uint free = 0;
    ulong free = 0;
    PERFINFO pi = new PERFINFO();
    if (GetPerformanceInfo(pi))
    {
    uint avail = (uint)pi.PhysicalAvailable;
    uint cache = (uint)pi.SystemCache;
    free = ( ((avail >= cache) ? avail - cache : cache - avail) * (uint)pi.PageSize ) >> 20;
    ulong avail = (ulong)pi.PhysicalAvailable;
    ulong cache = (ulong)pi.SystemCache;
    ulong page = (ulong)pi.PageSize;
    free = (page * ( (avail > cache) ? avail - cache : cache - avail) ) >> 20;
    /* To debug, change csc /target:winexe to /target:exe and uncomment the Console.WriteLine's */
    //Console.WriteLine("Total: {0,5}MB", (page*(ulong)pi.PhysicalTotal >> 20));
    //Console.WriteLine("Avail: {0,5}MB", (page*(ulong)pi.PhysicalAvailable >> 20));
    //Console.WriteLine("Cache: {0,5}MB", (page*(ulong)pi.SystemCache >> 20));
    //Console.WriteLine("Free: {0,5}MB", free);
    }
    if (free > target) return;
    //Console.WriteLine("Target:{0,5}MB - CLEARING!", target);
    RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE, true, false, ref retv);
    RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE, true, false, ref retv);
    NtSetSystemInformation(SystemMemoryListInformation, ref MemoryPurgeStandbyList, Marshal.SizeOf(MemoryPurgeStandbyList));
  4. @AveYo AveYo revised this gist Jun 1, 2019. 1 changed file with 53 additions and 40 deletions.
    93 changes: 53 additions & 40 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -1,8 +1,8 @@
    /* 2>nul || title FreeStandbyMemory.bat by AveYo v2018.12.03
    @echo off|| csc compiling snippet, advanced schedule, builtin add_remove - UPD: made optional system cache + working sets
    /* 2>nul || title FreeStandbyMemory.bat by AveYo v2019.06.01
    @echo off|| csc compiling snippet, advanced schedule, builtin add_remove - UPDATE: reliable free memory detection

    set/a CLEAR_EVERY_MINUTES=3
    set/a CLEAR_WHEN_UNDER_MB=1500
    set/a CLEAR_EVERY_MINUTES=1
    set/a CLEAR_WHEN_UNDER_MB=512
    set/a CLEAR_SYSTEMCACHEWS=0

    :: check_admin_rights
    @@ -41,7 +41,7 @@ powershell -noprofile -c "%sset% %stopexisting% $null=Set-ScheduledTask -TaskNam
    :: trigger task, force a manual clear and finish setup
    schtasks /Run /TN "FreeStandbyMemory"
    echo.
    echo Clearing StandbyMemory every %CLEAR_EVERY_MINUTES% minutes ONLY if available memory goes under %CLEAR_WHEN_UNDER_MB% MB
    echo Clearing StandbyMemory every %CLEAR_EVERY_MINUTES% minutes ONLY if free memory goes under %CLEAR_WHEN_UNDER_MB% MB
    echo Can force a clear manually from Command Prompt (Admin) by entering: freestandbymemory
    echo.
    echo ADDED! Run "%~nx0" again to remove compiled snippet and schedule!
    @@ -50,61 +50,74 @@ exit /b

    :: Based on idea from "PowerShell wrapper script for clear StandBy memory without RAMMap" by Alexander Korotkov
    :: Implemented SetSystemFileCacheSize and NtSetSystemInformation suggestions by Maks.K
    :: Using RtlAdjustPrivilege, GlobalMemoryStatusEx, force clear if no args, stripped output, sanitized by AveYo
    :: Using RtlAdjustPrivilege, GetPerformanceInfo, force clear if no args, stripped output, sanitized by AveYo
    */
    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Reflection;

    [assembly:AssemblyTitle("FreeStandbyMemory")]
    [assembly:AssemblyCompanyAttribute("AveYo")]
    [assembly:AssemblyVersionAttribute("2018.12.03")]
    [assembly:AssemblyCopyrightAttribute("AveYo")]
    [assembly:AssemblyVersionAttribute("2019.06.01")]

    namespace FreeStandbyMemory
    {
    class Program
    {
    const uint SE_INCREASE_QUOTA_PRIVILEGE = 0x00000005;
    const uint SE_PROF_SINGLE_PROCESS_PRIVILEGE = 0x0000000d;
    static bool retv = false;
    static int MemoryPurgeStandbyList = 0x0004;
    const int SystemFileCacheInformation = 0x0015;
    const int SystemMemoryListInformation = 0x0050;
    static int MemoryPurgeStandbyList = 0x0004;
    static bool retv = false;
    [DllImport("ntdll.dll")]
    static extern uint RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool RetValue);
    [DllImport("ntdll.dll")]
    static extern uint NtSetSystemInformation(int InfoClass, ref int Info, int Length);
    const uint SE_INCREASE_QUOTA_PRIVILEGE = 0x00000005;
    const uint SE_PROF_SINGLE_PROCESS_PRIVILEGE = 0x0000000d;
    [StructLayout(LayoutKind.Sequential)]
    private class PERFINFO
    {
    public uint cb;
    public UIntPtr CommitTotal;
    public UIntPtr CommitLimit;
    public UIntPtr CommitPeak;
    public UIntPtr PhysicalTotal;
    public UIntPtr PhysicalAvailable;
    public UIntPtr SystemCache;
    public UIntPtr KernelTotal;
    public UIntPtr KernelPaged;
    public UIntPtr KernelNonpaged;
    public UIntPtr PageSize;
    public uint HandleCount;
    public uint ProcessCount;
    public uint ThreadCount;
    public PERFINFO()
    {
    this.cb = (uint)Marshal.SizeOf(typeof(PERFINFO));
    }
    }
    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport( "psapi.dll", CharSet = CharSet.Auto, SetLastError = true )]
    static extern bool GetPerformanceInfo([In, Out] PERFINFO pi);
    [DllImport("psapi.dll")]
    static extern bool EmptyWorkingSet(IntPtr hwProc);
    [DllImport("kernel32.dll")]
    static extern bool SetSystemFileCacheSize(IntPtr MinimumFileCacheSize, IntPtr MaximumFileCacheSize, int Flags);
    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("kernel32.dll")]
    static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    private class MEMORYSTATUSEX
    {
    public uint dwLength;
    public uint dwMemoryLoad;
    public ulong ullTotalPhys;
    public ulong ullAvailPhys;
    public ulong ullTotalPageFile;
    public ulong ullAvailPageFile;
    public ulong ullTotalVirtual;
    public ulong ullAvailVirtual;
    public ulong ullAvailExtendedVirtual;
    public MEMORYSTATUSEX()
    {
    this.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
    }
    }
    [DllImport("ntdll.dll")]
    static extern uint RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool RetValue);
    [DllImport("ntdll.dll")]
    static extern uint NtSetSystemInformation(int InfoClass, ref int Info, int Length);

    static void Main(string[] args)
    {
    ulong availphysmem = (args.Length == 0) ? UInt64.MaxValue : Convert.ToUInt64(args[0]) * 1024 * 1024;
    ulong target = (args.Length == 0) ? UInt64.MaxValue : Convert.ToUInt64(args[0]);
    bool systemcachews = (args.Length == 0 || args.Length >= 2 && args[1] == "1");
    MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
    if (GlobalMemoryStatusEx(memStatus) && memStatus.ullAvailPhys > availphysmem) return;
    uint free = 0;
    PERFINFO pi = new PERFINFO();
    if (GetPerformanceInfo(pi))
    {
    uint avail = (uint)pi.PhysicalAvailable;
    uint cache = (uint)pi.SystemCache;
    free = ( ((avail >= cache) ? avail - cache : cache - avail) * (uint)pi.PageSize ) >> 20;
    }
    if (free > target) return;
    RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE, true, false, ref retv);
    RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE, true, false, ref retv);
    NtSetSystemInformation(SystemMemoryListInformation, ref MemoryPurgeStandbyList, Marshal.SizeOf(MemoryPurgeStandbyList));
    @@ -116,4 +129,4 @@ namespace FreeStandbyMemory
    }
    }
    }
    /*_*/
    /*_*/
  5. @AveYo AveYo revised this gist Dec 4, 2018. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -1,9 +1,9 @@
    /* 2>nul || title FreeStandbyMemory.bat by AveYo v2018.12.03
    @echo off|| csc compiling snippet, advanced schedule, builtin add_remove - UPD: systemcachews will also free system working sets
    @echo off|| csc compiling snippet, advanced schedule, builtin add_remove - UPD: made optional system cache + working sets

    set/a CLEAR_EVERY_MINUTES=3
    set/a CLEAR_WHEN_UNDER_MB=1500
    set/a CLEAR_SYSTEMCACHEWS=1
    set/a CLEAR_SYSTEMCACHEWS=0

    :: check_admin_rights
    reg query "HKEY_USERS\S-1-5-20\Environment" /v TEMP >nul 2>nul || (
  6. @AveYo AveYo revised this gist Dec 4, 2018. 1 changed file with 18 additions and 18 deletions.
    36 changes: 18 additions & 18 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -1,8 +1,7 @@
    /* 2>nul || title FreeStandbyMemory.bat by AveYo v2018.10.12 final
    @echo off|| UPDATE: now ultra fast at checking free ram! csc compiling snippet, advanced schedule, builtin add_remove
    :: 2018.11.20: increased default free ram threshold
    /* 2>nul || title FreeStandbyMemory.bat by AveYo v2018.12.03
    @echo off|| csc compiling snippet, advanced schedule, builtin add_remove - UPD: systemcachews will also free system working sets

    set/a CLEAR_EVERY_MINUTES=5
    set/a CLEAR_EVERY_MINUTES=3
    set/a CLEAR_WHEN_UNDER_MB=1500
    set/a CLEAR_SYSTEMCACHEWS=1

    @@ -54,12 +53,13 @@ exit /b
    :: Using RtlAdjustPrivilege, GlobalMemoryStatusEx, force clear if no args, stripped output, sanitized by AveYo
    */
    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Reflection;

    [assembly:AssemblyTitle("FreeStandbyMemory")]
    [assembly:AssemblyCompanyAttribute("AveYo")]
    [assembly:AssemblyVersionAttribute("2018.10.12")]
    [assembly:AssemblyVersionAttribute("2018.12.03")]

    namespace FreeStandbyMemory
    {
    @@ -75,6 +75,8 @@ namespace FreeStandbyMemory
    static extern uint RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool RetValue);
    [DllImport("ntdll.dll")]
    static extern uint NtSetSystemInformation(int InfoClass, ref int Info, int Length);
    [DllImport("psapi.dll")]
    static extern bool EmptyWorkingSet(IntPtr hwProc);
    [DllImport("kernel32.dll")]
    static extern bool SetSystemFileCacheSize(IntPtr MinimumFileCacheSize, IntPtr MaximumFileCacheSize, int Flags);
    [return: MarshalAs(UnmanagedType.Bool)]
    @@ -99,19 +101,17 @@ namespace FreeStandbyMemory
    }
    static void Main(string[] args)
    {
    UInt64 freemtarget = (args.Length == 0) ? UInt64.MaxValue : Convert.ToUInt64(args[0]) * 1024 * 1024;
    bool systemcachews = (args.Length == 0 || (args.Length >=2 && args[1] == "1"));
    try
    {
    MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
    if (GlobalMemoryStatusEx(memStatus) && memStatus.ullAvailPhys > freemtarget) return;
    RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE, true, false, ref retv);
    RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE, true, false, ref retv);
    if (systemcachews) SetSystemFileCacheSize(IntPtr.Subtract(IntPtr.Zero, 1), IntPtr.Subtract(IntPtr.Zero, 1), 0);
    NtSetSystemInformation(SystemMemoryListInformation, ref MemoryPurgeStandbyList, Marshal.SizeOf(MemoryPurgeStandbyList));
    }
    catch (Exception)
    {
    ulong availphysmem = (args.Length == 0) ? UInt64.MaxValue : Convert.ToUInt64(args[0]) * 1024 * 1024;
    bool systemcachews = (args.Length == 0 || args.Length >= 2 && args[1] == "1");
    MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
    if (GlobalMemoryStatusEx(memStatus) && memStatus.ullAvailPhys > availphysmem) return;
    RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE, true, false, ref retv);
    RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE, true, false, ref retv);
    NtSetSystemInformation(SystemMemoryListInformation, ref MemoryPurgeStandbyList, Marshal.SizeOf(MemoryPurgeStandbyList));
    if (systemcachews) {
    SetSystemFileCacheSize(IntPtr.Subtract(IntPtr.Zero, 1), IntPtr.Subtract(IntPtr.Zero, 1), 0);
    Process[] processlist = Process.GetProcesses(); // Also free system processes working sets:
    foreach(Process p in processlist) if (p.SessionId == 0) try { EmptyWorkingSet(p.Handle); } catch (Exception) {}
    }
    }
    }
  7. @AveYo AveYo revised this gist Nov 20, 2018. 1 changed file with 46 additions and 32 deletions.
    78 changes: 46 additions & 32 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -1,12 +1,12 @@
    /* 2>nul || title FreeStandbyMemory.bat by AveYo v2018.10.10
    @echo off|| csc compiling snippet, advanced schedule, builtin add_remove
    /* 2>nul || title FreeStandbyMemory.bat by AveYo v2018.10.12 final
    @echo off|| UPDATE: now ultra fast at checking free ram! csc compiling snippet, advanced schedule, builtin add_remove
    :: 2018.11.20: increased default free ram threshold

    set/a CLEAR_EVERY_MINUTES=5
    set/a CLEAR_WHEN_UNDER_MB=512
    set/a CLEAR_WHEN_UNDER_MB=1500
    set/a CLEAR_SYSTEMCACHEWS=1

    :: check_admin_rights
    title FreeStandbyMemory.bat
    reg query "HKEY_USERS\S-1-5-20\Environment" /v TEMP >nul 2>nul || (
    color 0e & echo. & echo PERMISSION DENIED! Right-click %~nx0 ^& Run as administrator
    timeout /t -1 & color 0f & title %COMSPEC% & exit/b
    @@ -23,42 +23,43 @@ schtasks /query /tn FreeStandbyMemory >nul 2>nul && (
    )

    :: compile c# snippet
    pushd %TEMP%
    pushd %~dp0
    del /f /q FreeStandbyMemory.exe >nul 2>nul
    for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%Windir%\Microsoft.NET\Framework\*csc.exe"') do set "csc="%%v""
    set mmi="%ProgramFiles(x86)%\Reference Assemblies\Microsoft\WMI\v1.0\Microsoft.Management.Infrastructure.dll"
    %csc% /out:FreeStandbyMemory.exe /target:winexe /platform:anycpu /optimize /nologo /reference:%mmi% "%~f0"
    if not exist FreeStandbyMemory.exe echo ERROR! Failed compiling c# snippet
    echo|set/p=FreeStandbyMemory.exe &copy /y FreeStandbyMemory.exe "%Windir%\FreeStandbyMemory.exe"
    echo HINT: Can force a clear manually from Command Prompt (Admin)
    %csc% /out:FreeStandbyMemory.exe /target:winexe /platform:anycpu /optimize /nologo "%~f0"
    if not exist FreeStandbyMemory.exe echo ERROR! Failed compiling c# snippet & timeout /t -1 & exit /b
    echo|set/p=FreeStandbyMemory.exe &copy /y FreeStandbyMemory.exe "%Windir%\FreeStandbyMemory.exe" &set "OUTDIR=%Windir%"
    if not exist "%Windir%\FreeStandbyMemory.exe" echo WARNING! Cannot copy FreeStandbyMemory.exe to %Windir%\ &set "OUTDIR=%CD%"

    :: setup advanced schedule
    set "task_run=FreeStandbyMemory.exe %CLEAR_WHEN_UNDER_MB% %CLEAR_SYSTEMCACHEWS%"
    :: setup advanced schedule - can afford higher priority after switching from wmi to winapi
    set "task_run=%OUTDIR%\FreeStandbyMemory.exe %CLEAR_WHEN_UNDER_MB% %CLEAR_SYSTEMCACHEWS%"
    set "schedule=/Create /RU "System" /NP /RL HIGHEST /F /SD "01/01/2001" /ST "01:00:00" "
    schtasks %schedule% /SC MINUTE /MO %CLEAR_EVERY_MINUTES% /TN "FreeStandbyMemory" /TR "%task_run%"
    set "sset=$s=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Priority 4 -StartWhenAvailable;"
    set "sset=$s=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Priority 1 -StartWhenAvailable;"
    set "stopexisting=$s.CimInstanceProperties['MultipleInstances'].Value=3;"
    powershell -noprofile -c "%sset% %stopexisting% $null=Set-ScheduledTask -TaskName FreeStandbyMemory -Settings $s"

    :: trigger task, force a manual clear and finish setup
    schtasks /Run /TN "FreeStandbyMemory"
    echo.
    echo Clearing StandbyMemory every %CLEAR_EVERY_MINUTES% minutes ONLY if available memory goes under %CLEAR_WHEN_UNDER_MB% MB
    echo Can force a clear manually from Command Prompt (Admin) by entering: freestandbymemory
    echo.
    echo ADDED! Run "%~nx0" again to remove compiled snippet and schedule!
    timeout /t -1
    exit /b

    :: Based on "PowerShell wrapper script for clear StandBy memory without RAMMap" by Alexander Korotkov
    :: Based on idea from "PowerShell wrapper script for clear StandBy memory without RAMMap" by Alexander Korotkov
    :: Implemented SetSystemFileCacheSize and NtSetSystemInformation suggestions by Maks.K
    :: Using RtlAdjustPrivilege, CimSession, force clear if no args, stripped output, sanitized by AveYo
    :: Using RtlAdjustPrivilege, GlobalMemoryStatusEx, force clear if no args, stripped output, sanitized by AveYo
    */
    using System;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using System.Reflection;
    using System.Security;
    using Microsoft.Management.Infrastructure;

    [assembly: AssemblyTitle("FreeStandbyMemory")]
    [assembly:AssemblyTitle("FreeStandbyMemory")]
    [assembly:AssemblyCompanyAttribute("AveYo")]
    [assembly:AssemblyVersionAttribute("2018.10.12")]

    namespace FreeStandbyMemory
    {
    @@ -70,27 +71,40 @@ namespace FreeStandbyMemory
    const int SystemMemoryListInformation = 0x0050;
    static int MemoryPurgeStandbyList = 0x0004;
    static bool retv = false;
    [DllImport("ntdll.dll"), SuppressUnmanagedCodeSecurity]
    [DllImport("ntdll.dll")]
    static extern uint RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool RetValue);
    [DllImport("ntdll.dll"), SuppressUnmanagedCodeSecurity]
    [DllImport("ntdll.dll")]
    static extern uint NtSetSystemInformation(int InfoClass, ref int Info, int Length);
    [DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity]
    [DllImport("kernel32.dll")]
    static extern bool SetSystemFileCacheSize(IntPtr MinimumFileCacheSize, IntPtr MaximumFileCacheSize, int Flags);
    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("kernel32.dll")]
    static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    private class MEMORYSTATUSEX
    {
    public uint dwLength;
    public uint dwMemoryLoad;
    public ulong ullTotalPhys;
    public ulong ullAvailPhys;
    public ulong ullTotalPageFile;
    public ulong ullAvailPageFile;
    public ulong ullTotalVirtual;
    public ulong ullAvailVirtual;
    public ulong ullAvailExtendedVirtual;
    public MEMORYSTATUSEX()
    {
    this.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
    }
    }
    static void Main(string[] args)
    {
    UInt64 freemtarget = (args.Length == 0) ? UInt64.MaxValue : Convert.ToUInt64(args[0]) * 1024;
    UInt64 freemtarget = (args.Length == 0) ? UInt64.MaxValue : Convert.ToUInt64(args[0]) * 1024 * 1024;
    bool systemcachews = (args.Length == 0 || (args.Length >=2 && args[1] == "1"));
    try
    {
    using (CimSession mySession = CimSession.Create(null))
    {
    string query = "SELECT FreePhysicalMemory FROM CIM_OperatingSystem";
    IEnumerable<CimInstance> queryInstances = mySession.QueryInstances(@"root\cimv2", "WQL", query);
    foreach (CimInstance instance in queryInstances)
    {
    if ((UInt64)instance.CimInstanceProperties["FreePhysicalMemory"].Value > freemtarget) return;
    }
    }
    MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
    if (GlobalMemoryStatusEx(memStatus) && memStatus.ullAvailPhys > freemtarget) return;
    RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE, true, false, ref retv);
    RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE, true, false, ref retv);
    if (systemcachews) SetSystemFileCacheSize(IntPtr.Subtract(IntPtr.Zero, 1), IntPtr.Subtract(IntPtr.Zero, 1), 0);
  8. @AveYo AveYo revised this gist Oct 10, 2018. 1 changed file with 46 additions and 50 deletions.
    96 changes: 46 additions & 50 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -1,97 +1,99 @@
    <# :: FreeStandbyMemory by AveYo, v6: fileless powershell task run, revised snippet, advanced schedule, builtin add_remove
    @echo off
    /* 2>nul || title FreeStandbyMemory.bat by AveYo v2018.10.10
    @echo off|| csc compiling snippet, advanced schedule, builtin add_remove

    set/a CLEAR_EVERY_MINUTES=5
    set/a CLEAR_WHEN_UNDER_MB=512
    set/a FILESYSTEMCACHEALSO=1
    set/a CLEAR_SYSTEMCACHEWS=1

    :: check_admin_rights
    title FreeStandbyMemory.bat
    reg query "HKEY_USERS\S-1-5-20\Environment" /v TEMP >nul 2>nul || (
    color 0c & echo. & echo PERMISSION DENIED! Right-click %~nx0 ^& Run as administrator
    timeout /t 60 & color 0f & title %COMSPEC% & exit/b
    color 0e & echo. & echo PERMISSION DENIED! Right-click %~nx0 ^& Run as administrator
    timeout /t -1 & color 0f & title %COMSPEC% & exit/b
    )

    :: add_remove whenever script is run again
    schtasks /query /tn FreeStandbyMemory >nul 2>nul && (
    echo.
    schtasks /Delete /TN "FreeStandbyMemory" /f 2>nul
    reg delete HKLM\Software\AveYo /v FreeStandbyMemory /f 2>nul
    del /f /q "%Windir%\FreeStandbyMemory.bat" 2>nul
    color 0c &echo. &echo REMOVED! Run script again to add fileless schedule!
    del /f /q "%Windir%\FreeStandbyMemory.exe" 2>nul
    color 0b &echo. &echo REMOVED! Run script again to recompile and add schedule!
    timeout /t -1 &color 0f &title %COMSPEC% &exit/b
    )

    echo.
    echo HINT: Can check if working by forcing a clear manually
    echo - directly in PowerShell (Admin):
    echo/ iex (Get-ItemProperty Registry::HKLM\SOFTWARE\AveYo).FreeStandbyMemory
    echo - directly in Command Prompt (Admin):
    echo/ powershell -noprofile -c "& {iex (Get-ItemProperty Registry::HKLM\SOFTWARE\AveYo).FreeStandbyMemory}"
    echo - with self-elevating via any cmd / powershell / .bat / .lnk:
    <nul set/p= powershell -noprofile -c "start powershell -ArgumentList '-noprofile -c &
    echo/ {iex (Get-ItemProperty Registry::HKLM\SOFTWARE\AveYo).FreeStandbyMemory}' -verb RunAs -WindowStyle Hidden"
    echo.
    :: compile c# snippet
    pushd %TEMP%
    del /f /q FreeStandbyMemory.exe >nul 2>nul
    for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%Windir%\Microsoft.NET\Framework\*csc.exe"') do set "csc="%%v""
    set mmi="%ProgramFiles(x86)%\Reference Assemblies\Microsoft\WMI\v1.0\Microsoft.Management.Infrastructure.dll"
    %csc% /out:FreeStandbyMemory.exe /target:winexe /platform:anycpu /optimize /nologo /reference:%mmi% "%~f0"
    if not exist FreeStandbyMemory.exe echo ERROR! Failed compiling c# snippet
    echo|set/p=FreeStandbyMemory.exe &copy /y FreeStandbyMemory.exe "%Windir%\FreeStandbyMemory.exe"
    echo HINT: Can force a clear manually from Command Prompt (Admin)

    :: setup advanced schedule
    set/a FREEMEM=1024*%CLEAR_WHEN_UNDER_MB%
    set "c1=if( (gwmi win32_OperatingSystem).FreePhysicalMemory -lt %FREEMEM% ) {"
    set "c2= iex (Get-ItemProperty Registry::HKLM\SOFTWARE\AveYo).FreeStandbyMemory }"
    set "task_run=FreeStandbyMemory.exe %CLEAR_WHEN_UNDER_MB% %CLEAR_SYSTEMCACHEWS%"
    set "schedule=/Create /RU "System" /NP /RL HIGHEST /F /SD "01/01/2001" /ST "01:00:00" "
    schtasks %schedule% /SC MINUTE /MO %CLEAR_EVERY_MINUTES% /TN "FreeStandbyMemory" /TR "powershell.exe -noprofile -c \"%c1%%c2%\""
    schtasks %schedule% /SC MINUTE /MO %CLEAR_EVERY_MINUTES% /TN "FreeStandbyMemory" /TR "%task_run%"
    set "sset=$s=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Priority 4 -StartWhenAvailable;"
    set "stopexisting=$s.CimInstanceProperties['MultipleInstances'].Value=3;"
    powershell -noprofile -c "%sset% %stopexisting% $null=Set-ScheduledTask -TaskName FreeStandbyMemory -Settings $s"

    :: export $Snippet to registry for fileless powershell task run
    if %FILESYSTEMCACHEALSO% GTR 0 (set "INCLUDE_FILESYSTEMCACHE=$true") else set "INCLUDE_FILESYSTEMCACHE=$false"
    set "r1=$txt=(([io.file]::ReadAllText(\"%~f0\") -split '/\*_\*/')[1]).replace(\"`r`n\",'');"
    set "r2=$Snippet='$Snippet='''+ $txt +'''; Add-Type -TypeDefinition $Snippet -Language CSharp;"
    set "r3=[FreeStandbyMemory.PInvoke]::ClearStandbyCache(%INCLUDE_FILESYSTEMCACHE%);'"
    set "reg_add=$key='HKLM:\Software\AveYo'; $null=New-Item -Path $key -Force; New-ItemProperty"
    powershell -noprofile -c "%r1% %r2% %r3%; %reg_add% -Force -Path $key -Name 'FreeStandbyMemory' -Value $Snippet;"

    :: trigger task, force a manual clear and finish setup
    schtasks /Run /TN "FreeStandbyMemory"
    powershell -noprofile -c "& {iex (Get-ItemProperty Registry::HKLM\SOFTWARE\AveYo).FreeStandbyMemory}"
    echo Clearing StandbyMemory every %CLEAR_EVERY_MINUTES% minutes ONLY if available memory goes under %CLEAR_WHEN_UNDER_MB% MB
    echo ADDED! Run "%~nx0" again to remove fileless schedule!
    echo ADDED! Run "%~nx0" again to remove compiled snippet and schedule!
    timeout /t -1
    exit /b

    # Based on "PowerShell wrapper script for clear StandBy memory without RAMMap" by Alexander Korotkov
    # Implemented SetSystemFileCacheSize and NtSetSystemInformation suggestions by Maks.K
    # Using RtlAdjustPrivilege, stripped output, sanitized by AveYo
    #>

    $Snippet = @"
    /*_*/
    :: Based on "PowerShell wrapper script for clear StandBy memory without RAMMap" by Alexander Korotkov
    :: Implemented SetSystemFileCacheSize and NtSetSystemInformation suggestions by Maks.K
    :: Using RtlAdjustPrivilege, CimSession, force clear if no args, stripped output, sanitized by AveYo
    */
    using System;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using System.Reflection;
    using System.Security;
    using Microsoft.Management.Infrastructure;

    [assembly: AssemblyTitle("FreeStandbyMemory")]

    namespace FreeStandbyMemory
    {
    public class PInvoke
    class Program
    {
    const uint SE_INCREASE_QUOTA_PRIVILEGE = 0x00000005;
    const uint SE_PROF_SINGLE_PROCESS_PRIVILEGE = 0x0000000d;
    const int SystemFileCacheInformation = 0x0015;
    const int SystemMemoryListInformation = 0x0050;
    static int MemoryPurgeStandbyList = 0x0004;
    static bool retv = false;
    [DllImport("ntdll.dll")]
    [DllImport("ntdll.dll"), SuppressUnmanagedCodeSecurity]
    static extern uint RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool RetValue);
    [DllImport("ntdll.dll")]
    [DllImport("ntdll.dll"), SuppressUnmanagedCodeSecurity]
    static extern uint NtSetSystemInformation(int InfoClass, ref int Info, int Length);
    [DllImport("kernel32")]
    [DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity]
    static extern bool SetSystemFileCacheSize(IntPtr MinimumFileCacheSize, IntPtr MaximumFileCacheSize, int Flags);
    public static void ClearStandbyCache(bool ClearFileSystemCache)
    static void Main(string[] args)
    {
    UInt64 freemtarget = (args.Length == 0) ? UInt64.MaxValue : Convert.ToUInt64(args[0]) * 1024;
    bool systemcachews = (args.Length == 0 || (args.Length >=2 && args[1] == "1"));
    try
    {
    using (CimSession mySession = CimSession.Create(null))
    {
    string query = "SELECT FreePhysicalMemory FROM CIM_OperatingSystem";
    IEnumerable<CimInstance> queryInstances = mySession.QueryInstances(@"root\cimv2", "WQL", query);
    foreach (CimInstance instance in queryInstances)
    {
    if ((UInt64)instance.CimInstanceProperties["FreePhysicalMemory"].Value > freemtarget) return;
    }
    }
    RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE, true, false, ref retv);
    RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE, true, false, ref retv);
    if (ClearFileSystemCache) SetSystemFileCacheSize(IntPtr.Subtract(IntPtr.Zero, 1), IntPtr.Subtract(IntPtr.Zero, 1), 0);
    if (systemcachews) SetSystemFileCacheSize(IntPtr.Subtract(IntPtr.Zero, 1), IntPtr.Subtract(IntPtr.Zero, 1), 0);
    NtSetSystemInformation(SystemMemoryListInformation, ref MemoryPurgeStandbyList, Marshal.SizeOf(MemoryPurgeStandbyList));
    }
    catch (Exception)
    @@ -101,9 +103,3 @@ namespace FreeStandbyMemory
    }
    }
    /*_*/
    "@

    Add-Type -TypeDefinition $Snippet -Language CSharp;

    [FreeStandbyMemory.PInvoke]::ClearStandbyCache($true);
    # 2018.10.02
  9. @AveYo AveYo revised this gist Oct 2, 2018. 1 changed file with 24 additions and 8 deletions.
    32 changes: 24 additions & 8 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    <# :: FreeStandbyMemory by AveYo, v5: fileless powershell task run, revised snippet, advanced schedule, builtin add_remove
    <# :: FreeStandbyMemory by AveYo, v6: fileless powershell task run, revised snippet, advanced schedule, builtin add_remove
    @echo off

    set/a CLEAR_EVERY_MINUTES=5
    @@ -14,30 +14,46 @@ reg query "HKEY_USERS\S-1-5-20\Environment" /v TEMP >nul 2>nul || (

    :: add_remove whenever script is run again
    schtasks /query /tn FreeStandbyMemory >nul 2>nul && (
    echo.
    schtasks /Delete /TN "FreeStandbyMemory" /f 2>nul
    reg delete HKLM\Software\AveYo /v FreeStandbyMemory /f 2>nul
    del /f /q "%Windir%\FreeStandbyMemory.bat" 2>nul
    color 0c &echo. &echo REMOVED! Run script again to add fileless schedule!
    timeout /t -1 &color 0f &title %COMSPEC% &exit/b
    )

    echo.
    echo HINT: Can check if working by forcing a clear manually
    echo - directly in PowerShell (Admin):
    echo/ iex (Get-ItemProperty Registry::HKLM\SOFTWARE\AveYo).FreeStandbyMemory
    echo - directly in Command Prompt (Admin):
    echo/ powershell -noprofile -c "& {iex (Get-ItemProperty Registry::HKLM\SOFTWARE\AveYo).FreeStandbyMemory}"
    echo - with self-elevating via any cmd / powershell / .bat / .lnk:
    <nul set/p= powershell -noprofile -c "start powershell -ArgumentList '-noprofile -c &
    echo/ {iex (Get-ItemProperty Registry::HKLM\SOFTWARE\AveYo).FreeStandbyMemory}' -verb RunAs -WindowStyle Hidden"
    echo.

    :: setup advanced schedule
    set/a FREEMEM=1024*%CLEAR_WHEN_UNDER_MB%
    set "ps_c=if( (gwmi win32_OperatingSystem).FreePhysicalMemory -lt %FREEMEM% ){ (Get-ItemProperty Registry::HKLM\SOFTWARE\AveYo).FreeStandbyMemory ^| iex }"
    schtasks /Create /RU "System" /SC MINUTE /MO %CLEAR_EVERY_MINUTES% /TN "FreeStandbyMemory" /TR "powershell.exe -noprofile -c \"%ps_c%\"" /SD "01/01/2001" /ST "01:00:00" /NP /RL HIGHEST /F
    set "stss=-AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 3) -Priority 4 -StartWhenAvailable"
    powershell -noprofile -c "$s=New-ScheduledTaskSettingsSet %stss%; $s.CimInstanceProperties['MultipleInstances'].Value=3; $null=Set-ScheduledTask -TaskName FreeStandbyMemory -Settings $s"
    set "c1=if( (gwmi win32_OperatingSystem).FreePhysicalMemory -lt %FREEMEM% ) {"
    set "c2= iex (Get-ItemProperty Registry::HKLM\SOFTWARE\AveYo).FreeStandbyMemory }"
    set "schedule=/Create /RU "System" /NP /RL HIGHEST /F /SD "01/01/2001" /ST "01:00:00" "
    schtasks %schedule% /SC MINUTE /MO %CLEAR_EVERY_MINUTES% /TN "FreeStandbyMemory" /TR "powershell.exe -noprofile -c \"%c1%%c2%\""
    set "sset=$s=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Priority 4 -StartWhenAvailable;"
    set "stopexisting=$s.CimInstanceProperties['MultipleInstances'].Value=3;"
    powershell -noprofile -c "%sset% %stopexisting% $null=Set-ScheduledTask -TaskName FreeStandbyMemory -Settings $s"

    :: export $Snippet to registry for fileless powershell task run
    if %FILESYSTEMCACHEALSO% GTR 0 (set "INCLUDE_FILESYSTEMCACHE=$true") else set "INCLUDE_FILESYSTEMCACHE=$false"
    set "r1=$txt=(([io.file]::ReadAllText(\"%~f0\") -split '/\*_\*/')[1]).replace(\"`r`n\",'');"
    set "r2=$Snippet='$Snippet='''+ $txt +'''; Add-Type -TypeDefinition $Snippet -Language CSharp;"
    set "r3=[FreeStandbyMemory.PInvoke]::ClearStandbyCache(%INCLUDE_FILESYSTEMCACHE%)'"
    set "r3=[FreeStandbyMemory.PInvoke]::ClearStandbyCache(%INCLUDE_FILESYSTEMCACHE%);'"
    set "reg_add=$key='HKLM:\Software\AveYo'; $null=New-Item -Path $key -Force; New-ItemProperty"
    powershell -noprofile -c "%r1% %r2% %r3%; %reg_add% -Force -Path $key -Name 'FreeStandbyMemory' -Value $Snippet;"

    :: trigger task and finish setup
    :: trigger task, force a manual clear and finish setup
    schtasks /Run /TN "FreeStandbyMemory"
    powershell -noprofile -c "& {iex (Get-ItemProperty Registry::HKLM\SOFTWARE\AveYo).FreeStandbyMemory}"
    echo Clearing StandbyMemory every %CLEAR_EVERY_MINUTES% minutes ONLY if available memory goes under %CLEAR_WHEN_UNDER_MB% MB
    echo ADDED! Run "%~nx0" again to remove fileless schedule!
    timeout /t -1
    @@ -90,4 +106,4 @@ namespace FreeStandbyMemory
    Add-Type -TypeDefinition $Snippet -Language CSharp;

    [FreeStandbyMemory.PInvoke]::ClearStandbyCache($true);
    exit # 2018.10.02
    # 2018.10.02
  10. @AveYo AveYo revised this gist Oct 2, 2018. 1 changed file with 34 additions and 27 deletions.
    61 changes: 34 additions & 27 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -1,49 +1,55 @@
    <# : FreeStandbyMemory by AveYo, v4: revised snippet, advanced schedule, built-in add-remove, under 4KB
    <# :: FreeStandbyMemory by AveYo, v5: fileless powershell task run, revised snippet, advanced schedule, builtin add_remove
    @echo off

    set/a CLEAR_EVERY_MINUTES=5
    set/a CLEAR_WHEN_UNDER_MB=512
    set/a FILESYSTEMCACHEALSO=1

    if %1.==schedule. (goto schedule) else goto setup

    :schedule
    for /f %%M in ('%SystemRoot%\System32\wbem\wmic.exe OS get FreePhysicalMemory') do set/a FreePhysicalMemory+=%%M >nul 2>nul
    set/a ClearWhenUnderKB=1024*%CLEAR_WHEN_UNDER_MB%
    if %FreePhysicalMemory% GTR %ClearWhenUnderKB% exit
    powershell -NoProfile -c "iex (${%~f0} | out-string)"
    exit

    :setup
    title FreeStandbyMemory
    :: check_admin_rights
    title FreeStandbyMemory.bat
    reg query "HKEY_USERS\S-1-5-20\Environment" /v TEMP >nul 2>nul || (
    color 0c & echo. & echo PERMISSION DENIED! Right-click %~nx0 ^& Run as administrator
    timeout /t 60 & color 0f & title %COMSPEC% & exit/b
    color 0c & echo. & echo PERMISSION DENIED! Right-click %~nx0 ^& Run as administrator
    timeout /t 60 & color 0f & title %COMSPEC% & exit/b
    )

    set "f0=%Windir%\FreeStandbyMemory.bat"
    :: add_remove whenever script is run again
    schtasks /query /tn FreeStandbyMemory >nul 2>nul && (
    schtasks /Delete /TN "FreeStandbyMemory" /f >nul 2>nul & rem del /f /q "%f0%"
    color 0c &echo REMOVED! Run script again to add persistent schedule!
    schtasks /Delete /TN "FreeStandbyMemory" /f 2>nul
    reg delete HKLM\Software\AveYo /v FreeStandbyMemory /f 2>nul
    del /f /q "%Windir%\FreeStandbyMemory.bat" 2>nul
    color 0c &echo. &echo REMOVED! Run script again to add fileless schedule!
    timeout /t -1 &color 0f &title %COMSPEC% &exit/b
    )

    echo CLEAR_EVERY_MINUTES=%CLEAR_EVERY_MINUTES%
    echo CLEAR_WHEN_UNDER_MB=%CLEAR_WHEN_UNDER_MB%

    if /i "%~f0"=="%f0%" (set "COPY2WINDIR=") else echo|set/p=%f0% &copy /y "%~f0" "%f0%" &set "COPY2WINDIR=yes"
    schtasks /Create /RU "System" /SC MINUTE /MO %CLEAR_EVERY_MINUTES% /TN "FreeStandbyMemory" /TR "cmd.exe /c call \"%f0%\" schedule" /SD "01/01/2010" /ST "01:00:00" /NP /RL HIGHEST /F
    :: setup advanced schedule
    set/a FREEMEM=1024*%CLEAR_WHEN_UNDER_MB%
    set "ps_c=if( (gwmi win32_OperatingSystem).FreePhysicalMemory -lt %FREEMEM% ){ (Get-ItemProperty Registry::HKLM\SOFTWARE\AveYo).FreeStandbyMemory ^| iex }"
    schtasks /Create /RU "System" /SC MINUTE /MO %CLEAR_EVERY_MINUTES% /TN "FreeStandbyMemory" /TR "powershell.exe -noprofile -c \"%ps_c%\"" /SD "01/01/2001" /ST "01:00:00" /NP /RL HIGHEST /F
    set "stss=-AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 3) -Priority 4 -StartWhenAvailable"
    powershell -c "$s=New-ScheduledTaskSettingsSet %stss%; $s.CimInstanceProperties['MultipleInstances'].Value=3; Set-ScheduledTask -TaskName FreeStandbyMemory -Settings $s"
    powershell -noprofile -c "$s=New-ScheduledTaskSettingsSet %stss%; $s.CimInstanceProperties['MultipleInstances'].Value=3; $null=Set-ScheduledTask -TaskName FreeStandbyMemory -Settings $s"

    :: export $Snippet to registry for fileless powershell task run
    if %FILESYSTEMCACHEALSO% GTR 0 (set "INCLUDE_FILESYSTEMCACHE=$true") else set "INCLUDE_FILESYSTEMCACHE=$false"
    set "r1=$txt=(([io.file]::ReadAllText(\"%~f0\") -split '/\*_\*/')[1]).replace(\"`r`n\",'');"
    set "r2=$Snippet='$Snippet='''+ $txt +'''; Add-Type -TypeDefinition $Snippet -Language CSharp;"
    set "r3=[FreeStandbyMemory.PInvoke]::ClearStandbyCache(%INCLUDE_FILESYSTEMCACHE%)'"
    set "reg_add=$key='HKLM:\Software\AveYo'; $null=New-Item -Path $key -Force; New-ItemProperty"
    powershell -noprofile -c "%r1% %r2% %r3%; %reg_add% -Force -Path $key -Name 'FreeStandbyMemory' -Value $Snippet;"

    :: trigger task and finish setup
    schtasks /Run /TN "FreeStandbyMemory"
    echo ADDED! Run %~f0 again to remove persistent schedule!
    echo Clearing StandbyMemory every %CLEAR_EVERY_MINUTES% minutes ONLY if available memory goes under %CLEAR_WHEN_UNDER_MB% MB
    echo ADDED! Run "%~nx0" again to remove fileless schedule!
    timeout /t -1
    exit /b

    # Based on "PowerShell wrapper script for clear StandBy memory without RAMMap" by Alexander Korotkov
    # Implemented SetSystemFileCacheSize and NtSetSystemInformation suggestions by Maks.K
    # Using RtlAdjustPrivilege, stripped output, sanitized by AveYo
    #>

    $Snippet = @"
    /*_*/
    using System;
    using System.Runtime.InteropServices;

    @@ -78,9 +84,10 @@ namespace FreeStandbyMemory
    }
    }
    }
    /*_*/
    "@

    Add-Type -TypeDefinition $Snippet -Language CSharp
    Add-Type -TypeDefinition $Snippet -Language CSharp;

    [FreeStandbyMemory.PInvoke]::ClearStandbyCache($true)
    # use $false to skip ClearFileSystemCache
    [FreeStandbyMemory.PInvoke]::ClearStandbyCache($true);
    exit # 2018.10.02
  11. @AveYo AveYo revised this gist Oct 2, 2018. 1 changed file with 21 additions and 32 deletions.
    53 changes: 21 additions & 32 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -1,16 +1,17 @@
    <# : FreeStandbyMemory by AveYo, v3: revised snippet, advanced schedule, built-in add-remove, under 4KB
    <# : FreeStandbyMemory by AveYo, v4: revised snippet, advanced schedule, built-in add-remove, under 4KB
    @echo off

    set CLEAR_EVERY_MINUTES=5
    set CLEAR_WHEN_UNDER_MB=512
    set/a CLEAR_EVERY_MINUTES=5
    set/a CLEAR_WHEN_UNDER_MB=512

    if %1.==schedule. (goto schedule) else goto setup

    :schedule
    for /f %%M in ('%SystemRoot%\System32\wbem\wmic.exe OS get FreePhysicalMemory') do set/a FreePhysicalMemory+=%%M >nul 2>nul
    set/a ClearWhenUnderKB=1024*%CLEAR_WHEN_UNDER_MB%
    if %FreePhysicalMemory% GTR %ClearWhenUnderKB% exit
    powershell -NoProfile -c "iex (${%~f0} | out-string)" & exit
    powershell -NoProfile -c "iex (${%~f0} | out-string)"
    exit

    :setup
    title FreeStandbyMemory
    @@ -21,8 +22,7 @@ reg query "HKEY_USERS\S-1-5-20\Environment" /v TEMP >nul 2>nul || (

    set "f0=%Windir%\FreeStandbyMemory.bat"
    schtasks /query /tn FreeStandbyMemory >nul 2>nul && (
    schtasks /Delete /TN "FreeStandbyMemory" /f >nul 2>nul
    rem del /f /q "%f0%"
    schtasks /Delete /TN "FreeStandbyMemory" /f >nul 2>nul & rem del /f /q "%f0%"
    color 0c &echo REMOVED! Run script again to add persistent schedule!
    timeout /t -1 &color 0f &title %COMSPEC% &exit/b
    )
    @@ -32,55 +32,45 @@ echo CLEAR_WHEN_UNDER_MB=%CLEAR_WHEN_UNDER_MB%

    if /i "%~f0"=="%f0%" (set "COPY2WINDIR=") else echo|set/p=%f0% &copy /y "%~f0" "%f0%" &set "COPY2WINDIR=yes"
    schtasks /Create /RU "System" /SC MINUTE /MO %CLEAR_EVERY_MINUTES% /TN "FreeStandbyMemory" /TR "cmd.exe /c call \"%f0%\" schedule" /SD "01/01/2010" /ST "01:00:00" /NP /RL HIGHEST /F
    set "stss=-AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 3) -Priority 5 -StartWhenAvailable"
    set "stss=-AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 3) -Priority 4 -StartWhenAvailable"
    powershell -c "$s=New-ScheduledTaskSettingsSet %stss%; $s.CimInstanceProperties['MultipleInstances'].Value=3; Set-ScheduledTask -TaskName FreeStandbyMemory -Settings $s"
    schtasks /Run /TN "FreeStandbyMemory"
    echo ADDED! Run %~f0 again to remove persistent schedule!
    timeout /t -1
    exit /b

    # Based on "PowerShell wrapper script for clear StandBy memory without RAMMap" by Alexander Korotkov
    # Implemented SetSystemFileCacheSize suggestion by Maks.K and RtlAdjustPrivilege by AveYo
    # Stripped output as it will run under System account
    # Implemented SetSystemFileCacheSize and NtSetSystemInformation suggestions by Maks.K
    # Using RtlAdjustPrivilege, stripped output, sanitized by AveYo
    #>
    $Snippet = @"
    using System;
    using System.Runtime.InteropServices;

    namespace FreeStandbyMemory
    {
    public class Program
    public class PInvoke
    {
    static bool retv = false;
    const uint SE_INCREASE_QUOTA_PRIVILEGE = 0x00000005;
    const uint SE_PROF_SINGLE_PROCESS_PRIVILEGE = 0x0000000d;
    const int SystemFileCacheInformation = 0x0015;
    const int SystemMemoryListInformation = 0x0050;
    const int MemoryPurgeStandbyList = 4;
    static int MemoryPurgeStandbyList = 0x0004;
    static bool retv = false;
    [DllImport("ntdll.dll")]
    public static extern int RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool RetValue);
    static extern uint RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool RetValue);
    [DllImport("ntdll.dll")]
    public static extern UInt32 NtSetSystemInformation(int InfoClass, IntPtr Info, int Length);
    [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool SetSystemFileCacheSize(IntPtr MinimumFileCacheSize, IntPtr MaximumFileCacheSize, Int32 Flags);
    static void Main(string[] args)
    {
    ClearStandbyCache(true);
    }
    static extern uint NtSetSystemInformation(int InfoClass, ref int Info, int Length);
    [DllImport("kernel32")]
    static extern bool SetSystemFileCacheSize(IntPtr MinimumFileCacheSize, IntPtr MaximumFileCacheSize, int Flags);
    public static void ClearStandbyCache(bool ClearFileSystemCache)
    {
    try
    {
    RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE,true,false,ref retv);
    RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE,true,false,ref retv);
    if (ClearFileSystemCache)
    {
    SetSystemFileCacheSize(IntPtr.Subtract(IntPtr.Zero,1), IntPtr.Subtract(IntPtr.Zero,1), 0);
    }
    int SystemInfoLength = Marshal.SizeOf(MemoryPurgeStandbyList);
    GCHandle gcHandle = GCHandle.Alloc(MemoryPurgeStandbyList, GCHandleType.Pinned);
    NtSetSystemInformation(SystemMemoryListInformation, gcHandle.AddrOfPinnedObject(), SystemInfoLength);
    gcHandle.Free();
    RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE, true, false, ref retv);
    RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE, true, false, ref retv);
    if (ClearFileSystemCache) SetSystemFileCacheSize(IntPtr.Subtract(IntPtr.Zero, 1), IntPtr.Subtract(IntPtr.Zero, 1), 0);
    NtSetSystemInformation(SystemMemoryListInformation, ref MemoryPurgeStandbyList, Marshal.SizeOf(MemoryPurgeStandbyList));
    }
    catch (Exception)
    {
    @@ -92,6 +82,5 @@ namespace FreeStandbyMemory

    Add-Type -TypeDefinition $Snippet -Language CSharp

    [FreeStandbyMemory.Program]::ClearStandbyCache($true)
    [FreeStandbyMemory.PInvoke]::ClearStandbyCache($true)
    # use $false to skip ClearFileSystemCache
    exit
  12. @AveYo AveYo revised this gist Oct 2, 2018. 1 changed file with 9 additions and 8 deletions.
    17 changes: 9 additions & 8 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    <# : FreeStandbyMemory by AveYo, v3: revised ps snippet, advanced schedule, built-in add-remove, under 4KB
    <# : FreeStandbyMemory by AveYo, v3: revised snippet, advanced schedule, built-in add-remove, under 4KB
    @echo off

    set CLEAR_EVERY_MINUTES=5
    @@ -9,8 +9,8 @@ if %1.==schedule. (goto schedule) else goto setup
    :schedule
    for /f %%M in ('%SystemRoot%\System32\wbem\wmic.exe OS get FreePhysicalMemory') do set/a FreePhysicalMemory+=%%M >nul 2>nul
    set/a ClearWhenUnderKB=1024*%CLEAR_WHEN_UNDER_MB%
    if %FreePhysicalMemory% GEQ %ClearWhenUnderKB% exit/b
    powershell -c "iex (${%~f0} | out-string)" & exit/b
    if %FreePhysicalMemory% GTR %ClearWhenUnderKB% exit
    powershell -NoProfile -c "iex (${%~f0} | out-string)" & exit

    :setup
    title FreeStandbyMemory
    @@ -31,17 +31,17 @@ echo CLEAR_EVERY_MINUTES=%CLEAR_EVERY_MINUTES%
    echo CLEAR_WHEN_UNDER_MB=%CLEAR_WHEN_UNDER_MB%

    if /i "%~f0"=="%f0%" (set "COPY2WINDIR=") else echo|set/p=%f0% &copy /y "%~f0" "%f0%" &set "COPY2WINDIR=yes"
    schtasks /Create /RU "System" /SC MINUTE /MO %CLEAR_EVERY_MINUTES% /TN "FreeStandbyMemory" /TR "\"%f0%\" schedule" /SD "01/01/2010" /ST "01:00:00" /NP /RL HIGHEST /F
    schtasks /Create /RU "System" /SC MINUTE /MO %CLEAR_EVERY_MINUTES% /TN "FreeStandbyMemory" /TR "cmd.exe /c call \"%f0%\" schedule" /SD "01/01/2010" /ST "01:00:00" /NP /RL HIGHEST /F
    set "stss=-AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 3) -Priority 5 -StartWhenAvailable"
    powershell -c "$s=New-ScheduledTaskSettingsSet %stss%; $s.CimInstanceProperties['MultipleInstances'].Value=3; Set-ScheduledTask -TaskName FreeStandbyMemory -Settings $s"
    schtasks /Run /TN "FreeStandbyMemory"
    echo ADDED! Run script again to remove persistent schedule!
    echo ADDED! Run %~f0 again to remove persistent schedule!
    timeout /t -1
    exit/b
    exit /b

    # Based on "PowerShell wrapper script for clear StandBy memory without RAMMap" by Alexander Korotkov
    # Implemented SetSystemFileCacheSize suggestion by Maks.K and RtlAdjustPrivilege by AveYo
    # Stripped output since it will run under Local System account
    # Stripped output as it will run under System account
    #>
    $Snippet = @"
    using System;
    @@ -93,4 +93,5 @@ namespace FreeStandbyMemory
    Add-Type -TypeDefinition $Snippet -Language CSharp

    [FreeStandbyMemory.Program]::ClearStandbyCache($true)
    # use $false to skip ClearFileSystemCache
    # use $false to skip ClearFileSystemCache
    exit
  13. @AveYo AveYo revised this gist Oct 2, 2018. 1 changed file with 60 additions and 133 deletions.
    193 changes: 60 additions & 133 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -1,169 +1,96 @@
    <# : batch wrapper and schedule by AveYo, v2
    @echo off &title FreeStandbyMemory
    <# : FreeStandbyMemory by AveYo, v3: revised ps snippet, advanced schedule, built-in add-remove, under 4KB
    @echo off

    set CLEAR_EVERY_MINUTES=5
    set CLEAR_WHEN_UNDER_MB=512

    if %1.==schedule. (goto schedule) else goto setup_schedule
    :need_admin_rights
    color 0c&echo. &echo PERMISSION DENIED! Right-click %~nx0 ^& Run as administrator &timeout /t 60 &color 0f&title %COMSPEC% &exit/b
    :setup_schedule
    reg query "HKEY_USERS\S-1-5-20\Environment" /v TEMP >nul 2>nul || goto need_admin_rights
    echo CLEAR_EVERY_MINUTES=%CLEAR_EVERY_MINUTES%
    echo CLEAR_WHEN_UNDER_MB=%CLEAR_WHEN_UNDER_MB%
    set "f0=%Windir%\FreeStandbyMemory.bat"
    if /i "%~f0"=="%f0%" (set "COPY2WINDIR=") else echo|set/p=%f0% &copy /y "%~f0" "%f0%" &set "COPY2WINDIR=yes"
    set "tn=FreeStandbyMemory" &set "mo=%CLEAR_EVERY_MINUTES%" &set "tr=cmd.exe /c call \"%f0%\" schedule"
    schtasks /Delete /TN "%tn%" /f
    schtasks /Create /RU "System" /sc MINUTE /MO %mo% /TN "%tn%" /TR "%tr%" /ST "12:00:00" /NP /F
    schtasks /Run /TN "%tn%"
    timeout /t -1
    exit/b
    if %1.==schedule. (goto schedule) else goto setup

    :schedule
    for /f "delims=" %%# in ('wmic path win32_Operatingsystem get FreePhysicalMemory /VALUE ^|find "Free"') do set "%%#"
    for /f %%M in ('%SystemRoot%\System32\wbem\wmic.exe OS get FreePhysicalMemory') do set/a FreePhysicalMemory+=%%M >nul 2>nul
    set/a ClearWhenUnderKB=1024*%CLEAR_WHEN_UNDER_MB%
    if %FreePhysicalMemory% GEQ %ClearWhenUnderKB% exit &rem v2: use wmic as it's faster to check freemem than launching ps instance
    type "%~f0" | powershell -c - &exit
    #>
    if %FreePhysicalMemory% GEQ %ClearWhenUnderKB% exit/b
    powershell -c "iex (${%~f0} | out-string)" & exit/b

    :setup
    title FreeStandbyMemory
    reg query "HKEY_USERS\S-1-5-20\Environment" /v TEMP >nul 2>nul || (
    color 0c & echo. & echo PERMISSION DENIED! Right-click %~nx0 ^& Run as administrator
    timeout /t 60 & color 0f & title %COMSPEC% & exit/b
    )

    set "f0=%Windir%\FreeStandbyMemory.bat"
    schtasks /query /tn FreeStandbyMemory >nul 2>nul && (
    schtasks /Delete /TN "FreeStandbyMemory" /f >nul 2>nul
    rem del /f /q "%f0%"
    color 0c &echo REMOVED! Run script again to add persistent schedule!
    timeout /t -1 &color 0f &title %COMSPEC% &exit/b
    )

    echo CLEAR_EVERY_MINUTES=%CLEAR_EVERY_MINUTES%
    echo CLEAR_WHEN_UNDER_MB=%CLEAR_WHEN_UNDER_MB%

    # PowerShell wrapper script for clear StandBy memory without RAMMap
    # https://gallery.technet.microsoft.com/scriptcenter/c-PowerShell-wrapper-6465e028
    # by Alexander Korotkov
    if /i "%~f0"=="%f0%" (set "COPY2WINDIR=") else echo|set/p=%f0% &copy /y "%~f0" "%f0%" &set "COPY2WINDIR=yes"
    schtasks /Create /RU "System" /SC MINUTE /MO %CLEAR_EVERY_MINUTES% /TN "FreeStandbyMemory" /TR "\"%f0%\" schedule" /SD "01/01/2010" /ST "01:00:00" /NP /RL HIGHEST /F
    set "stss=-AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 3) -Priority 5 -StartWhenAvailable"
    powershell -c "$s=New-ScheduledTaskSettingsSet %stss%; $s.CimInstanceProperties['MultipleInstances'].Value=3; Set-ScheduledTask -TaskName FreeStandbyMemory -Settings $s"
    schtasks /Run /TN "FreeStandbyMemory"
    echo ADDED! Run script again to remove persistent schedule!
    timeout /t -1
    exit/b

    $Source = @"
    # Based on "PowerShell wrapper script for clear StandBy memory without RAMMap" by Alexander Korotkov
    # Implemented SetSystemFileCacheSize suggestion by Maks.K and RtlAdjustPrivilege by AveYo
    # Stripped output since it will run under Local System account
    #>
    $Snippet = @"
    using System;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    using System.Security.Principal;

    namespace ClearStandbyList
    namespace FreeStandbyMemory
    {
    public class Program
    {
    const int SE_PRIVILEGE_ENABLED = 2;
    const string SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege";
    const string SE_PROFILE_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege";
    static bool retv = false;
    const uint SE_INCREASE_QUOTA_PRIVILEGE = 0x00000005;
    const uint SE_PROF_SINGLE_PROCESS_PRIVILEGE = 0x0000000d;
    const int SystemFileCacheInformation = 0x0015;
    const int SystemMemoryListInformation = 0x0050;
    const int MemoryPurgeStandbyList = 4;
    [DllImport("advapi32.dll", SetLastError = true)]
    internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
    [DllImport("advapi32.dll", SetLastError = true)]
    internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
    [DllImport("ntdll.dll")]
    public static extern int RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool RetValue);
    [DllImport("ntdll.dll")]
    public static extern UInt32 NtSetSystemInformation(int InfoClass, IntPtr Info, int Length);
    public static bool Is64BitMode()
    {
    return Marshal.SizeOf(typeof(IntPtr)) == 8;
    }
    [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool SetSystemFileCacheSize(IntPtr MinimumFileCacheSize, IntPtr MaximumFileCacheSize, Int32 Flags);
    static void Main(string[] args)
    {
    ClearFileSystemCache(true);
    ClearStandbyCache(true);
    }
    public static void ClearFileSystemCache(bool ClearStandbyCache)
    public static void ClearStandbyCache(bool ClearFileSystemCache)
    {
    try
    {
    if (SetIncreasePrivilege(SE_INCREASE_QUOTA_NAME))
    {
    uint num1;
    int SystemInfoLength;
    GCHandle gcHandle;
    if (!Is64BitMode())
    {
    SYSTEM_CACHE_INFORMATION cacheInformation = new SYSTEM_CACHE_INFORMATION();
    cacheInformation.MinimumWorkingSet = uint.MaxValue;
    cacheInformation.MaximumWorkingSet = uint.MaxValue;
    SystemInfoLength = Marshal.SizeOf(cacheInformation);
    gcHandle = GCHandle.Alloc(cacheInformation, GCHandleType.Pinned);
    num1 = NtSetSystemInformation(SystemFileCacheInformation, gcHandle.AddrOfPinnedObject(), SystemInfoLength);
    gcHandle.Free();
    }
    else
    {
    SYSTEM_CACHE_INFORMATION_64_BIT information64Bit = new SYSTEM_CACHE_INFORMATION_64_BIT();
    information64Bit.MinimumWorkingSet = -1L;
    information64Bit.MaximumWorkingSet = -1L;
    SystemInfoLength = Marshal.SizeOf(information64Bit);
    gcHandle = GCHandle.Alloc(information64Bit, GCHandleType.Pinned);
    num1 = NtSetSystemInformation(SystemFileCacheInformation, gcHandle.AddrOfPinnedObject(), SystemInfoLength);
    gcHandle.Free();
    }
    if (num1 != 0)
    throw new Exception("NtSetSystemInformation(SYSTEMCACHEINFORMATION) error: ", new Win32Exception(Marshal.GetLastWin32Error()));
    }
    if (ClearStandbyCache && SetIncreasePrivilege(SE_PROFILE_SINGLE_PROCESS_NAME))
    RtlAdjustPrivilege(SE_INCREASE_QUOTA_PRIVILEGE,true,false,ref retv);
    RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE,true,false,ref retv);
    if (ClearFileSystemCache)
    {

    int SystemInfoLength = Marshal.SizeOf(MemoryPurgeStandbyList);
    GCHandle gcHandle = GCHandle.Alloc(MemoryPurgeStandbyList, GCHandleType.Pinned);
    uint num2 = NtSetSystemInformation(SystemMemoryListInformation, gcHandle.AddrOfPinnedObject(), SystemInfoLength);
    gcHandle.Free();
    if (num2 != 0)
    throw new Exception("NtSetSystemInformation(SYSTEMMEMORYLISTINFORMATION) error: ", new Win32Exception(Marshal.GetLastWin32Error()));
    SetSystemFileCacheSize(IntPtr.Subtract(IntPtr.Zero,1), IntPtr.Subtract(IntPtr.Zero,1), 0);
    }
    int SystemInfoLength = Marshal.SizeOf(MemoryPurgeStandbyList);
    GCHandle gcHandle = GCHandle.Alloc(MemoryPurgeStandbyList, GCHandleType.Pinned);
    NtSetSystemInformation(SystemMemoryListInformation, gcHandle.AddrOfPinnedObject(), SystemInfoLength);
    gcHandle.Free();
    }
    catch (Exception ex)
    {
    Console.Write(ex.ToString());
    }
    }
    private static bool SetIncreasePrivilege(string privilegeName)
    {
    using (WindowsIdentity current = WindowsIdentity.GetCurrent(TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges))
    catch (Exception)
    {
    TokPriv1Luid newst;
    newst.Count = 1;
    newst.Luid = 0L;
    newst.Attr = SE_PRIVILEGE_ENABLED;
    if (!LookupPrivilegeValue(null, privilegeName, ref newst.Luid))
    throw new Exception("Error in LookupPrivilegeValue: ", new Win32Exception(Marshal.GetLastWin32Error()));
    int num = AdjustTokenPrivileges(current.Token, false, ref newst, 0, IntPtr.Zero, IntPtr.Zero) ? 1 : 0;
    if (num == 0)
    throw new Exception("Error in AdjustTokenPrivileges: ", new Win32Exception(Marshal.GetLastWin32Error()));
    return num != 0;
    }
    }
    }
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    struct SYSTEM_CACHE_INFORMATION
    {
    public uint CurrentSize;
    public uint PeakSize;
    public uint PageFaultCount;
    public uint MinimumWorkingSet;
    public uint MaximumWorkingSet;
    public uint Unused1;
    public uint Unused2;
    public uint Unused3;
    public uint Unused4;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    struct SYSTEM_CACHE_INFORMATION_64_BIT
    {
    public long CurrentSize;
    public long PeakSize;
    public long PageFaultCount;
    public long MinimumWorkingSet;
    public long MaximumWorkingSet;
    public long Unused1;
    public long Unused2;
    public long Unused3;
    public long Unused4;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    internal struct TokPriv1Luid
    {
    public int Count;
    public long Luid;
    public int Attr;
    }
    }
    "@

    Add-Type -TypeDefinition $Source -Language CSharp
    Add-Type -TypeDefinition $Snippet -Language CSharp

    [ClearStandbyList.Program]::ClearFileSystemCache($true)
    #
    [FreeStandbyMemory.Program]::ClearStandbyCache($true)
    # use $false to skip ClearFileSystemCache
  14. @AveYo AveYo created this gist Oct 2, 2018.
    169 changes: 169 additions & 0 deletions .FreeStandbyMemory.bat
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,169 @@
    <# : batch wrapper and schedule by AveYo, v2
    @echo off &title FreeStandbyMemory

    set CLEAR_EVERY_MINUTES=5
    set CLEAR_WHEN_UNDER_MB=512

    if %1.==schedule. (goto schedule) else goto setup_schedule
    :need_admin_rights
    color 0c&echo. &echo PERMISSION DENIED! Right-click %~nx0 ^& Run as administrator &timeout /t 60 &color 0f&title %COMSPEC% &exit/b
    :setup_schedule
    reg query "HKEY_USERS\S-1-5-20\Environment" /v TEMP >nul 2>nul || goto need_admin_rights
    echo CLEAR_EVERY_MINUTES=%CLEAR_EVERY_MINUTES%
    echo CLEAR_WHEN_UNDER_MB=%CLEAR_WHEN_UNDER_MB%
    set "f0=%Windir%\FreeStandbyMemory.bat"
    if /i "%~f0"=="%f0%" (set "COPY2WINDIR=") else echo|set/p=%f0% &copy /y "%~f0" "%f0%" &set "COPY2WINDIR=yes"
    set "tn=FreeStandbyMemory" &set "mo=%CLEAR_EVERY_MINUTES%" &set "tr=cmd.exe /c call \"%f0%\" schedule"
    schtasks /Delete /TN "%tn%" /f
    schtasks /Create /RU "System" /sc MINUTE /MO %mo% /TN "%tn%" /TR "%tr%" /ST "12:00:00" /NP /F
    schtasks /Run /TN "%tn%"
    timeout /t -1
    exit/b
    :schedule
    for /f "delims=" %%# in ('wmic path win32_Operatingsystem get FreePhysicalMemory /VALUE ^|find "Free"') do set "%%#"
    set/a ClearWhenUnderKB=1024*%CLEAR_WHEN_UNDER_MB%
    if %FreePhysicalMemory% GEQ %ClearWhenUnderKB% exit &rem v2: use wmic as it's faster to check freemem than launching ps instance
    type "%~f0" | powershell -c - &exit
    #>

    # PowerShell wrapper script for clear StandBy memory without RAMMap
    # https://gallery.technet.microsoft.com/scriptcenter/c-PowerShell-wrapper-6465e028
    # by Alexander Korotkov

    $Source = @"
    using System;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    using System.Security.Principal;

    namespace ClearStandbyList
    {
    public class Program
    {
    const int SE_PRIVILEGE_ENABLED = 2;
    const string SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege";
    const string SE_PROFILE_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege";
    const int SystemFileCacheInformation = 0x0015;
    const int SystemMemoryListInformation = 0x0050;
    const int MemoryPurgeStandbyList = 4;
    [DllImport("advapi32.dll", SetLastError = true)]
    internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
    [DllImport("advapi32.dll", SetLastError = true)]
    internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
    [DllImport("ntdll.dll")]
    public static extern UInt32 NtSetSystemInformation(int InfoClass, IntPtr Info, int Length);
    public static bool Is64BitMode()
    {
    return Marshal.SizeOf(typeof(IntPtr)) == 8;
    }
    static void Main(string[] args)
    {
    ClearFileSystemCache(true);
    }
    public static void ClearFileSystemCache(bool ClearStandbyCache)
    {
    try
    {
    if (SetIncreasePrivilege(SE_INCREASE_QUOTA_NAME))
    {
    uint num1;
    int SystemInfoLength;
    GCHandle gcHandle;
    if (!Is64BitMode())
    {
    SYSTEM_CACHE_INFORMATION cacheInformation = new SYSTEM_CACHE_INFORMATION();
    cacheInformation.MinimumWorkingSet = uint.MaxValue;
    cacheInformation.MaximumWorkingSet = uint.MaxValue;
    SystemInfoLength = Marshal.SizeOf(cacheInformation);
    gcHandle = GCHandle.Alloc(cacheInformation, GCHandleType.Pinned);
    num1 = NtSetSystemInformation(SystemFileCacheInformation, gcHandle.AddrOfPinnedObject(), SystemInfoLength);
    gcHandle.Free();
    }
    else
    {
    SYSTEM_CACHE_INFORMATION_64_BIT information64Bit = new SYSTEM_CACHE_INFORMATION_64_BIT();
    information64Bit.MinimumWorkingSet = -1L;
    information64Bit.MaximumWorkingSet = -1L;
    SystemInfoLength = Marshal.SizeOf(information64Bit);
    gcHandle = GCHandle.Alloc(information64Bit, GCHandleType.Pinned);
    num1 = NtSetSystemInformation(SystemFileCacheInformation, gcHandle.AddrOfPinnedObject(), SystemInfoLength);
    gcHandle.Free();
    }
    if (num1 != 0)
    throw new Exception("NtSetSystemInformation(SYSTEMCACHEINFORMATION) error: ", new Win32Exception(Marshal.GetLastWin32Error()));
    }
    if (ClearStandbyCache && SetIncreasePrivilege(SE_PROFILE_SINGLE_PROCESS_NAME))
    {

    int SystemInfoLength = Marshal.SizeOf(MemoryPurgeStandbyList);
    GCHandle gcHandle = GCHandle.Alloc(MemoryPurgeStandbyList, GCHandleType.Pinned);
    uint num2 = NtSetSystemInformation(SystemMemoryListInformation, gcHandle.AddrOfPinnedObject(), SystemInfoLength);
    gcHandle.Free();
    if (num2 != 0)
    throw new Exception("NtSetSystemInformation(SYSTEMMEMORYLISTINFORMATION) error: ", new Win32Exception(Marshal.GetLastWin32Error()));
    }
    }
    catch (Exception ex)
    {
    Console.Write(ex.ToString());
    }
    }
    private static bool SetIncreasePrivilege(string privilegeName)
    {
    using (WindowsIdentity current = WindowsIdentity.GetCurrent(TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges))
    {
    TokPriv1Luid newst;
    newst.Count = 1;
    newst.Luid = 0L;
    newst.Attr = SE_PRIVILEGE_ENABLED;
    if (!LookupPrivilegeValue(null, privilegeName, ref newst.Luid))
    throw new Exception("Error in LookupPrivilegeValue: ", new Win32Exception(Marshal.GetLastWin32Error()));
    int num = AdjustTokenPrivileges(current.Token, false, ref newst, 0, IntPtr.Zero, IntPtr.Zero) ? 1 : 0;
    if (num == 0)
    throw new Exception("Error in AdjustTokenPrivileges: ", new Win32Exception(Marshal.GetLastWin32Error()));
    return num != 0;
    }
    }
    }
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    struct SYSTEM_CACHE_INFORMATION
    {
    public uint CurrentSize;
    public uint PeakSize;
    public uint PageFaultCount;
    public uint MinimumWorkingSet;
    public uint MaximumWorkingSet;
    public uint Unused1;
    public uint Unused2;
    public uint Unused3;
    public uint Unused4;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    struct SYSTEM_CACHE_INFORMATION_64_BIT
    {
    public long CurrentSize;
    public long PeakSize;
    public long PageFaultCount;
    public long MinimumWorkingSet;
    public long MaximumWorkingSet;
    public long Unused1;
    public long Unused2;
    public long Unused3;
    public long Unused4;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    internal struct TokPriv1Luid
    {
    public int Count;
    public long Luid;
    public int Attr;
    }
    }
    "@

    Add-Type -TypeDefinition $Source -Language CSharp

    [ClearStandbyList.Program]::ClearFileSystemCache($true)
    #
    2 changes: 2 additions & 0 deletions .gitattributes
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    * text=auto
    * eol=crlf