$t = Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Api7 {
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool OpenProcessToken(IntPtr handle, uint access, ref IntPtr token);
[DllImport("kernel32.dll")]
public static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, ref long lpLuid);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool AdjustTokenPrivileges(IntPtr token, bool disableAll, ref TOKEN_PRIVILEGES NewState, uint BufferLength, IntPtr PreviousState, IntPtr ReturnLength);
[DllImport("kernel32.dll")]
public static extern uint GetLastError();
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr handle);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtSetSystemInformation(int infoClass, IntPtr Info, int len);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct TOKEN_PRIVILEGES {
public uint count;
public long luid;
public uint attr;
}
[StructLayout(LayoutKind.Sequential)]
public struct SystemCacheInformation
{
public long size;
public long peak;
public long count;
public long min;
public long max;
public long r1;
public long r2;
public long r3;
public long r4;
}
public static bool SetPrivilege(string name, bool enable) {
IntPtr hToken = IntPtr.Zero;
if (!OpenProcessToken(GetCurrentProcess(), 40, ref hToken))
return false;
long luid = 0;
if (!LookupPrivilegeValue(null, name, ref luid)) {
CloseHandle(hToken);
return false;
}
TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES {
count = 1,
luid = luid,
attr = (enable ? 2u : 0u)
};
bool result = AdjustTokenPrivileges(hToken, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
CloseHandle(hToken);
return result;
}
public static bool EmptySystemWorkingSet() {
if (!SetPrivilege("SeIncreaseQuotaPrivilege", true) || !SetPrivilege("SeProfileSingleProcessPrivilege", true))
return false;
int size = Marshal.SizeOf(typeof(SystemCacheInformation));
IntPtr buffer = Marshal.AllocHGlobal(size);
SystemCacheInformation sysInfo = new SystemCacheInformation {
min = -1L,
max = -1L
};
Marshal.StructureToPtr(sysInfo, buffer, false);
if (NtSetSystemInformation(21, buffer, size) != 0)
return false;
sysInfo.size = 4;
Marshal.StructureToPtr(sysInfo, buffer, false);
return NtSetSystemInformation(80, buffer, size) == 0;
}
}
"@ -PassThru
Get-Process | ForEach-Object { try { $_.MinWorkingSet = 1 } catch { }}
if ($t[0]::EmptySystemWorkingSet()) {
echo "Free RAM success"
} else {
echo "Free RAM error"
}