Skip to content

Instantly share code, notes, and snippets.

@neta1
Last active June 23, 2018 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neta1/836644d8875ff1a3221cc0ee2bd31484 to your computer and use it in GitHub Desktop.
Save neta1/836644d8875ff1a3221cc0ee2bd31484 to your computer and use it in GitHub Desktop.
Low Priority I/O @ PowerShell
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
public static class PriorityHelper
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern SafeProcessHandle OpenProcess(
ProcessAccessFlags processAccess,
bool bInheritHandle,
int processId
);
[DllImport("ntdll.dll", SetLastError = true)]
static extern int NtSetInformationProcess(SafeProcessHandle processHandle,
PROCESS_INFORMATION_CLASS processInformationClass, IntPtr processInformation,
int processInformationLength);
[Flags]
enum ProcessAccessFlags : uint
{
SetInformation = 0x00000200
}
enum PROCESS_INFORMATION_CLASS : uint
{
ProcessIoPriority = 33 // qs: ULONG
};
const uint LowIoPriority = 1u;
public static bool SetLowPriorityIO(int procId)
{
using (var hProc = OpenProcess(ProcessAccessFlags.SetInformation, false, procId))
{
if (hProc.IsInvalid) return false;
var ioPriority = IntPtr.Zero;
try
{
var size = Marshal.SizeOf<uint>();
ioPriority = Marshal.AllocHGlobal(size);
Marshal.WriteInt32(ioPriority, (int)LowIoPriority);
return NtSetInformationProcess(hProc, PROCESS_INFORMATION_CLASS.ProcessIoPriority, ioPriority, size) == 0;
}
finally
{
if (ioPriority != IntPtr.Zero) Marshal.FreeHGlobal(ioPriority);
}
}
}
}
Add-Type @"
using System;
using System.Runtime.InteropServices;
(snip)
}
}
"@
[PriorityHelper]::SetLowPriorityIO($PID)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment